/**
 * 坐庄系统管理器
 * 
 * 职责：
 * 1. 管理所有投注数据的存储和加载
 * 2. 计算开奖结果和盈亏分析
 * 3. 生成最大亏损排序分析
 * 4. 提供风险评估和最优开奖建议
 * 
 * 依赖模块：
 * - LotteryServer: 开奖计算引擎
 * - PayoutCalculator: 统一赔付计算器
 * - CommonUtils: 通用工具函数
 * 
 * @author 系统
 * @version 2.0.0
 * @since 2024-01-01
 */

import { STATE, StateManager } from './state.js';
import { CommonUtils, TailUtils, AnimalUtils, BanboRules, SeboUtils, BuzhongUtils } from './utils.js';
import { colorConfig, animalConfig } from './config.js';

export const BankerManager = {
    // 所有投注数据
    allBets: [],
    
    // 初始化坐庄系统
    init() {
        this.setupEventListeners();
        this.loadBetsFromStorage();
        this.updateDisplay();
    },
    
    // 设置事件监听器
    setupEventListeners() {
        // 刷新投注按钮
        const refreshBtn = document.getElementById('refreshBetsBtn');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => {
                this.loadBetsFromStorage();
                this.updateDisplay();
            });
        }
        
        // 清空所有投注按钮
        const clearBtn = document.getElementById('clearAllBetsBtn');
        if (clearBtn) {
            clearBtn.addEventListener('click', () => {
                if (confirm('确定要清空所有投注数据吗？此操作不可恢复！')) {
                    this.clearAllBets();
                }
            });
        }
        
        // 计算风险按钮
        const calculateBtn = document.getElementById('calculateRiskBtn');
        if (calculateBtn) {
            calculateBtn.addEventListener('click', () => {
                this.calculateRiskAnalysis();
            });
        }
        
        // 风险分析控制
        const showOnlyRiskCheckbox = document.getElementById('showOnlyRiskNumbers');
        const riskSortSelect = document.getElementById('riskSortBy');
        
        if (showOnlyRiskCheckbox) {
            showOnlyRiskCheckbox.addEventListener('change', () => {
                this.updateRiskDisplay();
            });
        }
        
        if (riskSortSelect) {
            riskSortSelect.addEventListener('change', () => {
                this.updateRiskDisplay();
            });
        }
        
        // 开奖结果计算相关事件
        const calculateActualBtn = document.getElementById('calculateActualResult');
        const clearDrawBtn = document.getElementById('clearDrawInput');
        const fillSampleBtn = document.getElementById('fillSampleDraw');
        
        if (calculateActualBtn) {
            calculateActualBtn.addEventListener('click', () => {
                this.calculateActualResult();
            });
        }
        
        if (clearDrawBtn) {
            clearDrawBtn.addEventListener('click', () => {
                this.clearDrawInput();
            });
        }
        
        if (fillSampleBtn) {
            fillSampleBtn.addEventListener('click', () => {
                this.fillSampleDraw();
            });
        }
        
        // 服务器开奖逻辑相关事件
        const useOptimalBtn = document.getElementById('useOptimalResult');
        
        if (useOptimalBtn) {
            useOptimalBtn.addEventListener('click', () => {
                this.useOptimalResult();
            });
        }
        
        // 测试和局按钮
        const testHejuBtn = document.getElementById('testHejuBtn');
        if (testHejuBtn) {
            testHejuBtn.addEventListener('click', () => {
                this.testHejuCalculation();
            });
        }
    },
    
    // 从localStorage加载投注数据
    loadBetsFromStorage() {
        try {
            const storedBets = localStorage.getItem('banker_all_bets');
            if (storedBets) {
                this.allBets = JSON.parse(storedBets);
                // 从localStorage加载投注数据
                
                // 验证和修复数据结构
                this.validateAndFixBetData();
            } else {
                this.allBets = [];
            }
        } catch (error) {
            console.error('加载投注数据失败:', error);
            this.allBets = [];
        }
    },
    
    // 验证和修复投注数据结构
    validateAndFixBetData() {
        let fixedCount = 0;
        this.allBets.forEach(bet => {
            // 修复特码直选投注的错误sub字段
            if (bet.type === 'numbers' && bet.game === 'tema' && bet.sub === 'liangmian') {
                bet.sub = 'zhixuan';
                fixedCount++;
                                    // 修复了特码直选投注的sub字段
            }
            
            // 修复特码两面投注的错误type字段
            if (bet.type === 'numbers' && bet.game === 'tema' && bet.sub === 'liangmian' && bet.sideType) {
                bet.type = 'sides';
                fixedCount++;
                                    // 修复了特码两面投注的type字段
            }
        });
        
        if (fixedCount > 0) {
            // 数据结构修复完成
            this.saveBetsToStorage(); // 保存修复后的数据
        }
    },
    
    // 保存投注数据到localStorage
    saveBetsToStorage() {
        try {
            localStorage.setItem('banker_all_bets', JSON.stringify(this.allBets));
        } catch (error) {
            console.error('保存投注数据失败:', error);
        }
    },
    
    // 添加新投注
    addBet(bet) {
        // 为投注添加时间戳和唯一ID
        const betWithTimestamp = {
            ...bet,
            timestamp: Date.now(),
            bankerId: `banker_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
        };
        
        this.allBets.push(betWithTimestamp);
        this.saveBetsToStorage();
        
        // 如果当前在坐庄系统页面，更新显示
        const bankerContent = document.getElementById('bankerContent');
        if (bankerContent && bankerContent.style.display !== 'none') {
            this.updateDisplay();
        }
    },
    
    // 删除投注
    deleteBet(bankerId) {
        this.allBets = this.allBets.filter(bet => bet.bankerId !== bankerId);
        this.saveBetsToStorage();
        this.updateDisplay();
    },
    
    // 清空所有投注
    clearAllBets() {
        this.allBets = [];
        this.saveBetsToStorage();
        this.updateDisplay();
    },
    
    // 更新显示
    updateDisplay() {
        this.updateSummary();
        this.updateBetsTable();
        this.updateGameStatistics();
        this.calculateRiskAnalysis();
        // 自动生成亏损排序
        this.autoGenerateLossRanking();
    },

    // 自动生成亏损排序
    autoGenerateLossRanking() {
        try {
            // 检查是否有投注数据
            if (!this.allBets || this.allBets.length === 0) {
                // 如果没有投注数据，显示提示信息
                const summaryEl = document.getElementById('lossRankingSummary');
                const tableEl = document.getElementById('lossRankingTable');
                
                if (summaryEl) {
                    summaryEl.innerHTML = '<div class="no-data-message"><i class="fas fa-info-circle"></i>暂无投注数据，请先进行投注或点击"生成测试数据"按钮</div>';
                }
                if (tableEl) {
                    tableEl.innerHTML = '<div class="no-data-message"><i class="fas fa-plus-circle"></i>添加投注后将自动显示所有开奖结果的亏损排序</div>';
                }
                return;
            }
            
            // 确保LotteryServer存在并重置统计
            if (typeof window.LotteryServer !== 'undefined') {
                window.LotteryServer.resetStatistics();
                
                // 添加投注到统计
                this.allBets.forEach(bet => {
                    const convertedBet = this.convertBetForLotteryServer(bet);
                    window.LotteryServer.addBetToStatistics(convertedBet);
                });
                
                // 使用自己的计算逻辑生成亏损排序数据
                const lossRankingData = this.calculateMaxLossRanking();
                const lossSummary = this.calculateMaxLossSummary(lossRankingData);
                
                if (lossRankingData && lossSummary) {
                    this.displayLossRanking(lossRankingData, lossSummary);
                } else {
                    // 未能获取到亏损排序数据
                }
            } else {
                console.error('LotteryServer未定义，无法生成亏损排序');
                const summaryEl = document.getElementById('lossRankingSummary');
                const tableEl = document.getElementById('lossRankingTable');
                
                if (summaryEl) {
                    summaryEl.innerHTML = '<div class="no-data-message">系统错误：LotteryServer未加载</div>';
                }
                if (tableEl) {
                    tableEl.innerHTML = '<div class="no-data-message">请刷新页面重试</div>';
                }
            }
        } catch (error) {
            console.error('自动生成亏损排序错误:', error);
            // 显示错误信息
            const summaryEl = document.getElementById('lossRankingSummary');
            const tableEl = document.getElementById('lossRankingTable');
            
            if (summaryEl) {
                summaryEl.innerHTML = '<div class="no-data-message">生成失败：' + error.message + '</div>';
            }
            if (tableEl) {
                tableEl.innerHTML = '<div class="no-data-message">请检查投注数据或刷新页面</div>';
            }
        }
    },
    
    // 更新汇总信息
    updateSummary() {
        const totalBetCount = this.allBets.length;
        const totalBetAmount = this.allBets.reduce((sum, bet) => sum + (bet.amount * bet.count), 0);
        const maxPotentialPayout = this.allBets.reduce((sum, bet) => {
            return sum + this.calculatePotentialPayout(bet);
        }, 0);
        const expectedProfit = totalBetAmount - maxPotentialPayout;
        
        // 更新DOM
        const totalBetCountEl = document.getElementById('totalBetCount');
        const totalBetAmountEl = document.getElementById('totalBetAmount');
        const maxPotentialPayoutEl = document.getElementById('maxPotentialPayout');
        const expectedProfitEl = document.getElementById('expectedProfit');
        
        if (totalBetCountEl) totalBetCountEl.textContent = totalBetCount;
        if (totalBetAmountEl) totalBetAmountEl.textContent = `¥${totalBetAmount}`;
        if (maxPotentialPayoutEl) maxPotentialPayoutEl.textContent = `¥${maxPotentialPayout}`;
        if (expectedProfitEl) {
            expectedProfitEl.textContent = `¥${expectedProfit}`;
            expectedProfitEl.className = `summary-value ${expectedProfit >= 0 ? 'profit' : 'danger'}`;
        }
    },
    
    // 更新投注表格
    updateBetsTable() {
        const tableBody = document.getElementById('bankerTableBody');
        if (!tableBody) return;
        
        if (this.allBets.length === 0) {
            tableBody.innerHTML = '<div style="text-align: center; padding: 20px; color: #666;">暂无投注数据</div>';
            return;
        }
        
        tableBody.innerHTML = this.allBets.map(bet => {
            const totalAmount = bet.amount * bet.count;
            const potentialPayout = this.calculatePotentialPayout(bet);
            
            return `
                <div class="table-row">
                    <span title="${bet.bankerId}">${bet.bankerId.substr(-6)}</span>
                    <span>${this.getGameTypeName(bet)}</span>
                    <span class="bet-description" title="${bet.description}">${bet.description}</span>
                    <span>${bet.count}</span>
                    <span>¥${bet.amount}</span>
                    <span>¥${totalAmount}</span>
                    <span>${bet.odds}</span>
                    <span>¥${potentialPayout}</span>
                    <span>
                        <button class="delete-bet-banker" onclick="BankerManager.deleteBet('${bet.bankerId}')">
                            删除
                        </button>
                    </span>
                </div>
            `;
        }).join('');
    },
    
    // 获取玩法类型名称
    getGameTypeName(bet) {
        const gameNames = {
            'tema': '特码',
            'zhengma': '正码',
            'lianma': '连码',
            'banbo': '半波',
            'shengxiao': '生肖',
            'weishu': '尾数',
            'buzhong': '不中',
            'sebo': '色波'
        };
        
        return gameNames[bet.game] || bet.game;
    },

    // 统一的潜在赔付计算方法（已重构为使用全局PayoutCalculator）
    calculatePotentialPayout(bet) {
        // 强制使用全局统一的赔付计算器
        return window.PayoutCalculator.calculatePotentialPayout(bet);
    },



    // 统一的中奖赔付计算方法（用于实际开奖时）
    // 与潜在赔付计算逻辑完全相同，确保预期和实际计算一致
    calculateWinPayout(bet, drawNumber = null) {
        // 如果提供了开奖号码，检查是否为和局
        if (drawNumber === 49 && bet.game === 'tema' && bet.sub === 'liangmian') {
            const winResult = this.checkTemaLiangmianWin(bet, drawNumber);
            if (winResult === 'he') {
                // 和局：退本金
                return bet.amount * bet.count;
            }
        }
        
        return this.calculatePotentialPayout(bet);
    },
    
    // 更新玩法统计
    updateGameStatistics() {
        const gameStatsGrid = document.getElementById('gameStatsGrid');
        if (!gameStatsGrid) return;
        
        // 按玩法分组统计
        const gameStats = {};
        
        this.allBets.forEach(bet => {
            const gameType = bet.game;
            if (!gameStats[gameType]) {
                gameStats[gameType] = {
                    count: 0,
                    totalAmount: 0,
                    totalPayout: 0
                };
            }
            
            const betAmount = bet.amount * bet.count;
            gameStats[gameType].count += bet.count;
            gameStats[gameType].totalAmount += betAmount;
            
            // 使用统一的潜在赔付计算方法
            const potentialPayout = this.calculatePotentialPayout(bet);
            gameStats[gameType].totalPayout += potentialPayout;
        });
        
        if (Object.keys(gameStats).length === 0) {
            gameStatsGrid.innerHTML = '<div style="text-align: center; padding: 20px; color: #666;">暂无统计数据</div>';
            return;
        }
        
        gameStatsGrid.innerHTML = Object.entries(gameStats).map(([gameType, stats]) => {
            const profit = stats.totalAmount - stats.totalPayout;
            
            return `
                <div class="game-stat-card">
                    <div class="game-stat-title">${this.getGameTypeName({game: gameType})}</div>
                    <div class="game-stat-details">
                        <span>投注注数:</span>
                        <span class="game-stat-amount">${stats.count}注</span>
                    </div>
                    <div class="game-stat-details">
                        <span>投注金额:</span>
                        <span class="game-stat-amount">¥${stats.totalAmount}</span>
                    </div>
                    <div class="game-stat-details">
                        <span>潜在赔付:</span>
                        <span class="game-stat-amount">¥${stats.totalPayout}</span>
                    </div>
                    <div class="game-stat-details">
                        <span>预计盈亏:</span>
                        <span class="game-stat-amount" style="color: ${profit >= 0 ? '#28a745' : '#dc3545'}">
                            ¥${profit}
                        </span>
                    </div>
                </div>
            `;
        }).join('');
    },
    
    // 计算风险分析
    calculateRiskAnalysis() {
        const riskData = {};
        
        // 初始化所有号码的风险数据
        for (let i = 1; i <= 49; i++) {
            riskData[i] = {
                number: i,
                totalIncome: 0, // 总收入（所有投注金额）
                totalPayout: 0, // 总赔付
                netProfit: 0    // 净利润
            };
        }
        
        // 计算每个号码的风险
        this.allBets.forEach(bet => {
            const betAmount = bet.amount * bet.count;
            
            // 为每个号码计算如果开出该号码的盈亏
            for (let number = 1; number <= 49; number++) {
                riskData[number].totalIncome += betAmount;
                
                // 检查这个投注是否会在该号码开出时中奖
                const willWin = this.checkBetWin(bet, number);
                if (willWin) {
                    // 使用统一的中奖赔付计算方法，传入开奖号码处理和局
                    const winPayout = this.calculateWinPayout(bet, number);
                    riskData[number].totalPayout += winPayout;
                }
            }
        });
        
        // 计算净利润
        Object.values(riskData).forEach(data => {
            data.netProfit = data.totalIncome - data.totalPayout;
        });
        
        this.riskData = riskData;
        this.updateRiskDisplay();
    },
    
    // 检查投注是否中奖
    checkBetWin(bet, drawNumber) {
        // 模拟开奖结果：以drawNumber为特码，随机生成6个正码
        const zhengmaNumbers = this.generateMockZhengma(drawNumber);
        const allNumbers = [...zhengmaNumbers, drawNumber];
        
        switch (bet.type) {
            case 'tema':
                if (bet.sub === 'zhixuan') {
                    return bet.numbers && bet.numbers.includes(drawNumber);
                } else if (bet.sub === 'liangmian') {
                    const result = this.checkTemaLiangmianWin(bet, drawNumber);
                    // 和局也算"中奖"（退本金）
                    return result === true || result === 'he';
                }
                break;
                
            case 'zhengma':
                if (bet.sub === 'renxuan') {
                    return bet.numbers && bet.numbers.some(num => zhengmaNumbers.includes(num));
                } else if (bet.sub.includes('te')) {
                    const position = parseInt(bet.sub.replace('zheng', '').replace('te', ''));
                    return bet.numbers && bet.numbers.includes(zhengmaNumbers[position - 1]);
                }
                break;
                
            case 'sebo':
                return SeboUtils.checkSeboWin(bet.sebo, zhengmaNumbers, drawNumber).isWin;
                
            case 'shengxiao':
                return this.checkAnimalBetWin(bet, allNumbers, drawNumber);
                
            case 'banbo':
                return BanboRules.checkBanboWin(bet.selectedBanbos || [bet.banboType], drawNumber).length > 0;
                
            case 'buzhong':
                return BuzhongUtils.checkBuzhongWin(bet.numbers, allNumbers, bet.sub);
                
            case 'weishu':
                return this.checkTailBetWin(bet, allNumbers, drawNumber);
                
            case 'lianma':
                return this.checkLianmaBetWin(bet, zhengmaNumbers, drawNumber);
        }
        
        return false;
    },
    
    // 生成模拟正码（用于风险计算）
    generateMockZhengma(temaNumber) {
        const numbers = [];
        const availableNumbers = [];
        
        // 生成1-49中除了特码外的号码
        for (let i = 1; i <= 49; i++) {
            if (i !== temaNumber) {
                availableNumbers.push(i);
            }
        }
        
        // 随机选择6个作为正码
        while (numbers.length < 6 && availableNumbers.length > 0) {
            const randomIndex = Math.floor(Math.random() * availableNumbers.length);
            numbers.push(availableNumbers.splice(randomIndex, 1)[0]);
        }
        
        return numbers.sort((a, b) => a - b);
    },
    
    // 检查特码两面投注
    checkTemaLiangmianWin(bet, drawNumber) {
        if (!bet.sideType) return false;
        
        // 特码49和局处理：只有家禽/野兽/波色算，其他都不算
        if (drawNumber === 49) {
            switch (bet.sideType) {
                case 'jiaqin':
                    return this.isJiaqin(drawNumber);
                case 'yeshou':
                    return this.isYeshou(drawNumber);
                case 'hongbo':
                case 'red':
                    return CommonUtils.getNumberColor(drawNumber) === 'red';
                case 'lanbo':
                case 'blue':
                    return CommonUtils.getNumberColor(drawNumber) === 'blue';
                case 'lvbo':
                case 'green':
                    return CommonUtils.getNumberColor(drawNumber) === 'green';
                default:
                    // 特码49时，大小单双、大单大双小单小双、合大合小合单合双都不算（和局退本金）
                    return 'he'; // 返回特殊值表示和局
            }
        }
        
        // 添加家禽野兽调试日志
        if (bet.sideType === 'jiaqin' || bet.sideType === 'yeshou') {
                    // 检查特码两面投注
        }
        
        switch (bet.sideType) {
            case 'da':
                return drawNumber >= 25; // 大：25-48（49和局）
            case 'xiao':
                return drawNumber <= 24; // 小：1-24（49和局）
            case 'dan':
                return drawNumber % 2 === 1; // 单（49和局）
            case 'shuang':
                return drawNumber % 2 === 0; // 双（49和局）
            case 'dadan':
                return drawNumber >= 25 && drawNumber % 2 === 1; // 大单（49和局）
            case 'dashuang':
                return drawNumber >= 25 && drawNumber % 2 === 0; // 大双（49和局）
            case 'xiaodan':
                return drawNumber <= 24 && drawNumber % 2 === 1; // 小单（49和局）
            case 'xiaoshuang':
                return drawNumber <= 24 && drawNumber % 2 === 0; // 小双（49和局）
            case 'hongbo':
            case 'red':
                return CommonUtils.getNumberColor(drawNumber) === 'red';
            case 'lanbo':
            case 'blue':
                return CommonUtils.getNumberColor(drawNumber) === 'blue';
            case 'lvbo':
            case 'green':
                return CommonUtils.getNumberColor(drawNumber) === 'green';
            case 'weida':
                return drawNumber >= 40; // 尾大：40-48（49和局）
            case 'weixiao':
                return drawNumber <= 9; // 尾小：1-9（49和局）
            case 'hedan':
                // 合单：各位数字相加为单数（49和局）
                const sum = Math.floor(drawNumber / 10) + (drawNumber % 10);
                return sum % 2 === 1;
            case 'heshuang':
                // 合双：各位数字相加为双数（49和局）
                const sum2 = Math.floor(drawNumber / 10) + (drawNumber % 10);
                return sum2 % 2 === 0;
            case 'heda':
                // 合大：各位数字相加大于6（49和局）
                const sum3 = Math.floor(drawNumber / 10) + (drawNumber % 10);
                return sum3 > 6;
            case 'hexiao':
                // 合小：各位数字相加小于等于6（49和局）
                const sum4 = Math.floor(drawNumber / 10) + (drawNumber % 10);
                return sum4 <= 6;
            case 'jiaqin':
                // 家禽：牛、马、羊、鸡、狗、猪
                const jiaqinResult = this.isJiaqin(drawNumber);
                if (bet.sideType === 'jiaqin') {
                                // 家禽检查
                }
                return jiaqinResult;
            case 'yeshou':
                // 野兽：鼠、虎、龙、蛇、猴、兔
                const yeshouResult = this.isYeshou(drawNumber);
                if (bet.sideType === 'yeshou') {
                                // 野兽检查
                }
                return yeshouResult;
            default:
                return false;
        }
    },

    // 检查是否为家禽
    isJiaqin(number) {
        // 检查是否为家禽
        const shengxiao = CommonUtils.getShengxiao(number);
        const jiaqinAnimals = ['牛', '马', '羊', '鸡', '狗', '猪'];
        const result = jiaqinAnimals.includes(shengxiao);
        
        // 额外验证：直接通过号码检查
        const jiaqinNumbers = [
            5, 17, 29, 41,    // 牛
            12, 24, 36, 48,   // 马
            11, 23, 35, 47,   // 羊
            9, 21, 33, 45,    // 鸡
            8, 20, 32, 44,    // 狗
            7, 19, 31, 43     // 猪
        ];
        const directCheck = jiaqinNumbers.includes(number);
        
        // 验证两种方法的一致性
        if (result !== directCheck) {
            console.error('警告：家禽检查方法结果不一致！');
        }
        
        return result;
    },

    // 检查是否为野兽
    isYeshou(number) {
        const shengxiao = CommonUtils.getShengxiao(number);
        return ['鼠', '虎', '龙', '蛇', '猴', '兔'].includes(shengxiao);
    },
    
    // 检查生肖投注
    checkAnimalBetWin(bet, allNumbers, temaNumber) {
        if (!bet.animals || bet.animals.length === 0) return false;
        
        const zhengmaNumbers = allNumbers.slice(0, 6); // 前6个是正码
        
        switch (bet.sub) {
            case 'texiao':
                // 特肖：特码的生肖在选中的生肖中
                return AnimalUtils.checkTexiaoWin(bet.animals, temaNumber);
            case 'yixiao':
                // 一肖：开奖号码中有任意一个生肖在选中的生肖中
                return AnimalUtils.checkYixiaoWin(bet.animals, allNumbers);
            case 'erxiaolian':
                // 二肖连：选中的2个生肖都在开奖号码中
                return AnimalUtils.checkLianxiaoWin(bet.animals, allNumbers, 2);
            case 'sanxiaolian':
                // 三肖连：选中的3个生肖都在开奖号码中
                return AnimalUtils.checkLianxiaoWin(bet.animals, allNumbers, 3);
            case 'sixiaolian':
                // 四肖连：选中的4个生肖都在开奖号码中
                return AnimalUtils.checkLianxiaoWin(bet.animals, allNumbers, 4);
            case 'zhengxiao':
                // 正肖：基于正码的生肖匹配
                const result = AnimalUtils.checkZhengxiaoWin(bet.animals, zhengmaNumbers);
                return result.isWin;
            case 'hexiaozhong':
                // 合肖中：特码的生肖在选中的生肖中（49号和局）
                const hexiaoResult = AnimalUtils.checkHexiaozhongWin(bet.animals, temaNumber);
                return hexiaoResult.isWin;
            case 'hexiaobuzhong':
                // 合肖不中：特码的生肖不在选中的生肖中（49号和局）
                const hexiaobuzhongResult = AnimalUtils.checkHexiaobuzhongWin(bet.animals, temaNumber);
                return hexiaobuzhongResult.isWin;
            default:
                return false;
        }
    },
    
    // 检查尾数投注
    checkTailBetWin(bet, allNumbers, temaNumber) {
        switch (bet.sub) {
            case 'tematowei':
                // 特码头尾
                return TailUtils.checkTematoweiWin(bet.tails || bet.heads, bet.tailType || 'tail', allNumbers);
            case 'erweilian':
            case 'sanweilian':
            case 'siweilian':
                // 连尾
                return TailUtils.checkLianweiWin(bet.tails, allNumbers, bet.sub, bet.tailCombinations);
            case 'zhengteweishu':
                // 正特尾数
                return TailUtils.checkZhengteweishuWin(bet.tails, allNumbers);
            default:
                return false;
        }
    },
    
    // 检查连码投注
    checkLianmaBetWin(bet, zhengmaNumbers, temaNumber) {
        if (!bet.numbers || bet.numbers.length === 0) return false;
        
        const allNumbers = [...zhengmaNumbers, temaNumber];
        
        switch (bet.sub) {
            case 'sanquanzhong':
                // 三全中：选中的3个号码都在正码中
                return bet.numbers.length === 3 && bet.numbers.every(num => zhengmaNumbers.includes(num));
            case 'sanzhonger':
                // 三中二：选中的3个号码中有2个在正码中
                const matchCount2 = bet.numbers.filter(num => zhengmaNumbers.includes(num)).length;
                return matchCount2 >= 2;
            case 'erquanzhong':
                // 二全中：选中的2个号码都在正码中
                return bet.numbers.length === 2 && bet.numbers.every(num => zhengmaNumbers.includes(num));
            case 'erzhongte':
                // 二中特：选中的2个号码中有1个是特码，另1个在正码中
                const hasTemashu = bet.numbers.includes(temaNumber);
                const zhengmaMatch = bet.numbers.filter(num => zhengmaNumbers.includes(num)).length;
                return hasTemashu && zhengmaMatch >= 1;
            case 'techuan':
                // 特串：选中的号码中包含特码
                return bet.numbers.includes(temaNumber);
            default:
                return false;
        }
    },
    
    // 更新风险显示
    updateRiskDisplay() {
        const riskGrid = document.getElementById('riskGrid');
        const showOnlyRisk = document.getElementById('showOnlyRiskNumbers')?.checked;
        const sortBy = document.getElementById('riskSortBy')?.value || 'loss_desc';
        
        if (!riskGrid || !this.riskData) return;
        
        let displayData = Object.values(this.riskData);
        
        // 过滤数据
        if (showOnlyRisk) {
            displayData = displayData.filter(data => data.netProfit < 0);
        }
        
        // 排序数据
        displayData.sort((a, b) => {
            switch (sortBy) {
                case 'loss_desc':
                    return a.netProfit - b.netProfit; // 亏损从高到低
                case 'loss_asc':
                    return b.netProfit - a.netProfit; // 亏损从低到高
                case 'number_asc':
                    return a.number - b.number; // 号码从小到大
                default:
                    return a.netProfit - b.netProfit;
            }
        });
        
        if (displayData.length === 0) {
            riskGrid.innerHTML = '<div style="text-align: center; padding: 20px; color: #666;">暂无风险数据</div>';
            return;
        }
        
        riskGrid.innerHTML = displayData.map(data => {
            const isProfit = data.netProfit >= 0;
            const isHighRisk = data.netProfit < -1000; // 亏损超过1000为高风险
            
            let className = 'risk-item';
            if (isHighRisk) className += ' high-risk';
            else if (isProfit) className += ' profit';
            else className += ' loss';
            
            return `
                <div class="${className}">
                    <div class="risk-number">${data.number.toString().padStart(2, '0')}</div>
                    <div class="risk-amount ${isProfit ? 'profit' : 'loss'}">
                        ${isProfit ? '+' : ''}¥${data.netProfit}
                    </div>
                </div>
            `;
        }).join('');
    },
    
    // 填入示例开奖数据
    fillSampleDraw() {
        // 使用图片中的示例数据：第2025070期 09 29 49 24 11 23 + 30
        document.getElementById('drawPeriod').value = '2025070';
        document.getElementById('zhengma1').value = '09';
        document.getElementById('zhengma2').value = '29';
        document.getElementById('zhengma3').value = '49';
        document.getElementById('zhengma4').value = '24';
        document.getElementById('zhengma5').value = '11';
        document.getElementById('zhengma6').value = '23';
        document.getElementById('tema').value = '30';
    },
    
    // 清空开奖输入
    clearDrawInput() {
        document.getElementById('drawPeriod').value = '';
        document.getElementById('zhengma1').value = '';
        document.getElementById('zhengma2').value = '';
        document.getElementById('zhengma3').value = '';
        document.getElementById('zhengma4').value = '';
        document.getElementById('zhengma5').value = '';
        document.getElementById('zhengma6').value = '';
        document.getElementById('tema').value = '';
        
        // 隐藏结果面板
        const resultPanel = document.getElementById('actualResultPanel');
        if (resultPanel) {
            resultPanel.style.display = 'none';
        }
    },
    
    // 计算实际开奖结果
    calculateActualResult() {
        // 获取输入的开奖号码
        const drawData = this.getDrawInputData();
        if (!drawData) return;
        
        // 开始计算实际结果
        
        // 计算实际盈亏
        const result = this.calculateActualProfitLoss(drawData);
        
        // 显示结果
        this.displayActualResult(drawData, result);
    },
    
    // 获取开奖输入数据
    getDrawInputData() {
        const period = document.getElementById('drawPeriod').value.trim();
        const zhengma1 = parseInt(document.getElementById('zhengma1').value);
        const zhengma2 = parseInt(document.getElementById('zhengma2').value);
        const zhengma3 = parseInt(document.getElementById('zhengma3').value);
        const zhengma4 = parseInt(document.getElementById('zhengma4').value);
        const zhengma5 = parseInt(document.getElementById('zhengma5').value);
        const zhengma6 = parseInt(document.getElementById('zhengma6').value);
        const tema = parseInt(document.getElementById('tema').value);
        
        // 验证输入
        const zhengmaNumbers = [zhengma1, zhengma2, zhengma3, zhengma4, zhengma5, zhengma6];
        
        if (!period) {
            alert('请输入期号');
            return null;
        }
        
        if (zhengmaNumbers.some(num => isNaN(num) || num < 1 || num > 49)) {
            alert('请输入有效的正码号码（1-49）');
            return null;
        }
        
        if (isNaN(tema) || tema < 1 || tema > 49) {
            alert('请输入有效的特码号码（1-49）');
            return null;
        }
        
        // 检查号码重复
        const allNumbers = [...zhengmaNumbers, tema];
        const uniqueNumbers = [...new Set(allNumbers)];
        if (uniqueNumbers.length !== allNumbers.length) {
            alert('开奖号码不能重复');
            return null;
        }
        
        return {
            period: period,
            zhengmaNumbers: zhengmaNumbers,
            temaNumber: tema,
            allNumbers: allNumbers
        };
    },
    
    // 计算实际盈亏
    calculateActualProfitLoss(drawData) {
        let totalIncome = 0;
        let totalPayout = 0;
        let winCount = 0;
        const winDetails = [];
        
        // 遍历所有投注
        this.allBets.forEach(bet => {
            const betAmount = bet.amount * bet.count;
            totalIncome += betAmount;
            
            // 检查是否中奖
            const isWin = this.checkBetWinActual(bet, drawData);
            
            if (isWin) {
                // 使用统一的中奖赔付计算方法，传入特码号码处理和局
                const payout = this.calculateWinPayout(bet, drawData.temaNumber);
                totalPayout += payout;
                winCount++;
                
                winDetails.push({
                    bet: bet,
                    payout: payout,
                    profit: payout - betAmount
                });
            }
        });
        
        const netProfit = totalIncome - totalPayout;
        
        return {
            totalIncome: totalIncome,
            totalPayout: totalPayout,
            netProfit: netProfit,
            winCount: winCount,
            winDetails: winDetails
        };
    },
    
    // 检查投注是否中奖（使用实际开奖数据）
    checkBetWinActual(bet, drawData) {
        const { zhengmaNumbers, temaNumber, allNumbers } = drawData;
        
        // 添加调试日志
        if (bet.sideType === 'jiaqin' || bet.sideType === 'yeshou') {
                    // 检查家禽/野兽投注
        }
        
        switch (bet.game) {
            case 'tema':
                if (bet.sub === 'zhixuan') {
                    return bet.numbers && bet.numbers.includes(temaNumber);
                } else if (bet.sub === 'liangmian') {
                    const result = this.checkTemaLiangmianWin(bet, temaNumber);
                    if (bet.sideType === 'jiaqin' || bet.sideType === 'yeshou') {
                        // 特码两面检查完成
                    }
                    // 和局也算"中奖"（退本金）
                    return result === true || result === 'he';
                }
                break;
                
            case 'zhengma':
                if (bet.sub === 'renxuan') {
                    return bet.numbers && bet.numbers.some(num => zhengmaNumbers.includes(num));
                } else if (bet.sub.includes('te')) {
                    const position = parseInt(bet.sub.replace('zheng', '').replace('te', ''));
                    return bet.numbers && bet.numbers.includes(zhengmaNumbers[position - 1]);
                }
                break;
                
            case 'sebo':
                return SeboUtils.checkSeboWin(bet.sebo, zhengmaNumbers, temaNumber).isWin;
                
            case 'shengxiao':
                return this.checkAnimalBetWin(bet, allNumbers, temaNumber);
                
            case 'banbo':
                return BanboRules.checkBanboWin(bet.selectedBanbos || [bet.banboType], temaNumber).length > 0;
                
            case 'buzhong':
                return BuzhongUtils.checkBuzhongWin(bet.numbers, allNumbers, bet.sub);
                
            case 'weishu':
                return this.checkTailBetWin(bet, allNumbers, temaNumber);
                
            case 'lianma':
                return this.checkLianmaBetWin(bet, zhengmaNumbers, temaNumber);
        }
                
        // 处理两面投注（可能使用sideType字段）
        if (bet.sideType) {
            if (bet.sideType === 'jiaqin' || bet.sideType === 'yeshou') {
                // 处理特码两面投注
            }
            
            if (bet.position === 'tema') {
                const result = this.checkTemaLiangmianWin(bet, temaNumber);
                if (bet.sideType === 'jiaqin' || bet.sideType === 'yeshou') {
                    // 特码两面sideType检查完成
                }
                return result;
            } else {
                // 正码两面
                const position = parseInt(bet.position);
                if (position >= 1 && position <= 6) {
                    return this.checkTemaLiangmianWin(bet, zhengmaNumbers[position - 1]);
                }
            }
        }
                
        // 处理总肖投注
        if (bet.zongxiaoType) {
                return AnimalUtils.checkZongxiaoWin(bet.zongxiaoType, allNumbers);
        }
        
        return false;
    },
    
    // 显示实际结果
    displayActualResult(drawData, result) {
        const resultPanel = document.getElementById('actualResultPanel');
        if (!resultPanel) return;
        
        // 显示结果面板
        resultPanel.style.display = 'block';
        
        // 更新汇总数据
        const totalIncomeEl = document.getElementById('actualTotalIncome');
        const totalPayoutEl = document.getElementById('actualTotalPayout');
        const netProfitEl = document.getElementById('actualNetProfit');
        const winCountEl = document.getElementById('actualWinCount');
        
        if (totalIncomeEl) totalIncomeEl.textContent = `¥${result.totalIncome}`;
        if (totalPayoutEl) totalPayoutEl.textContent = `¥${result.totalPayout}`;
        if (netProfitEl) {
            netProfitEl.textContent = `¥${result.netProfit}`;
            netProfitEl.className = `result-value ${result.netProfit >= 0 ? 'profit' : 'danger'}`;
        }
        if (winCountEl) winCountEl.textContent = `${result.winCount}注`;
        
        // 更新中奖详情
        this.displayWinDetails(drawData, result.winDetails);
    },
    
    // 显示中奖详情
    displayWinDetails(drawData, winDetails) {
        const winDetailsTable = document.getElementById('winDetailsTable');
        if (!winDetailsTable) return;
        
        if (winDetails.length === 0) {
            winDetailsTable.innerHTML = '<div style="text-align: center; padding: 20px; color: #666;">本期无中奖投注</div>';
            return;
        }
        
        winDetailsTable.innerHTML = `
            <div class="win-detail-header">
                <span>投注ID</span>
                <span>玩法</span>
                <span>投注内容</span>
                <span>投注金额</span>
                <span>赔付金额</span>
                <span>净盈利</span>
            </div>
            ${winDetails.map(detail => {
                const bet = detail.bet;
                return `
                    <div class="win-detail-row">
                        <span>${bet.bankerId ? bet.bankerId.substr(-6) : 'N/A'}</span>
                        <span>${this.getGameTypeName(bet)} <span class="win-badge">中</span></span>
                        <span class="win-detail-description">${bet.description}</span>
                        <span>¥${bet.amount * bet.count}</span>
                        <span class="result-value profit">¥${detail.payout}</span>
                        <span class="result-value profit">¥${detail.profit}</span>
                    </div>
                `;
            }).join('')}
        `;
    },
    
    // 服务器开奖逻辑方法
    
    // 存储最优开奖结果
    optimalResult: null,
    
    // 计算最优开奖
    calculateOptimalLottery() {
        if (this.allBets.length === 0) {
            alert('暂无投注数据，无法计算最优开奖！');
            return;
        }
        
        try {
            // 重置开奖服务器统计
            window.LotteryServer.resetStatistics();
            
            // 将所有投注添加到开奖服务器统计中
            this.allBets.forEach(bet => {
                // 转换投注格式为lottery-server期望的格式
                const convertedBet = this.convertBetForLotteryServer(bet);
                window.LotteryServer.addBetToStatistics(convertedBet);
            });
            
            // 获取最优开奖结果
            this.optimalResult = window.LotteryServer.getBestLotteryResult();
            
            if (this.optimalResult) {
                this.displayOptimalResult();
                // 最优开奖结果计算完成
            } else {
                alert('计算最优开奖失败！');
            }
        } catch (error) {
            console.error('计算最优开奖错误:', error);
            alert('计算最优开奖时发生错误：' + error.message);
        }
    },
    
    // 显示最优开奖结果
    displayOptimalResult() {
        if (!this.optimalResult) return;
        
        const panel = document.getElementById('optimalResultPanel');
        const temaEl = document.getElementById('optimalTema');
        const zhengmaEl = document.getElementById('optimalZhengma');
        const payoutEl = document.getElementById('optimalPayout');
        const profitEl = document.getElementById('optimalProfit');
        
        if (panel && temaEl && zhengmaEl && payoutEl && profitEl) {
            // 显示面板
            panel.style.display = 'block';
            
            // 从正确的数据结构中获取数据
            const lotteryResult = this.optimalResult.lotteryResult;
            const profitLoss = this.optimalResult.profitLoss;
            const netProfit = this.optimalResult.netProfit;
            
            // 更新数据
            temaEl.textContent = lotteryResult.tema.toString().padStart(2, '0');
            zhengmaEl.textContent = lotteryResult.zhengma.map(n => n.toString().padStart(2, '0')).join(', ');
            payoutEl.textContent = `¥${profitLoss.totalPayout}`;
            
            profitEl.textContent = `¥${netProfit}`;
            profitEl.className = `result-value ${netProfit >= 0 ? 'profit' : 'danger'}`;
        }
    },
    
    // 显示详细分析
    showLotteryAnalysis() {
        if (this.allBets.length === 0) {
            alert('暂无投注数据，无法进行分析！');
            return;
        }
        
        try {
            // 重置开奖服务器统计
            window.LotteryServer.resetStatistics();
            
            // 将所有投注添加到开奖服务器统计中
            this.allBets.forEach(bet => {
                // 转换投注格式为lottery-server期望的格式
                const convertedBet = this.convertBetForLotteryServer(bet);
                window.LotteryServer.addBetToStatistics(convertedBet);
            });
            
            // 获取分析报告
            const analysisReport = window.LotteryServer.getLotteryAnalysisReport();
            
            if (analysisReport) {
                this.displayAnalysisReport(analysisReport);
                // 分析报告生成完成
            } else {
                alert('获取分析报告失败！');
            }
        } catch (error) {
            console.error('分析报告错误:', error);
            alert('生成分析报告时发生错误：' + error.message);
        }
    },

    // 显示亏损排序
    showLossRanking() {
        if (this.allBets.length === 0) {
            if (confirm('暂无投注数据，是否生成测试数据进行分析？')) {
                this.generateTestData();
                this.updateDisplay();
            } else {
                return;
            }
        }
        
        // 清空缓存，确保数据一致性
        this._combinationCache = {};
        
        try {
            // 重置开奖服务器统计
            window.LotteryServer.resetStatistics();
            
            // 将所有投注添加到开奖服务器统计中
            this.allBets.forEach(bet => {
                // 转换投注格式为lottery-server期望的格式
                const convertedBet = this.convertBetForLotteryServer(bet);
                // 转换投注数据
                window.LotteryServer.addBetToStatistics(convertedBet);
            });
            
            // 计算真正的最大亏损排序数据
            const lossRankingData = this.calculateMaxLossRanking();
            const lossSummary = this.calculateMaxLossSummary(lossRankingData);
            
            if (lossRankingData && lossSummary) {
                this.displayLossRanking(lossRankingData, lossSummary);
            } else {
                alert('获取亏损排序数据失败！');
            }
        } catch (error) {
            console.error('亏损排序错误:', error);
            alert('生成亏损排序时发生错误：' + error.message);
        }
    },

    // 计算真正的最大亏损排序
    calculateMaxLossRanking() {
        const results = [];
        const totalBetAmount = window.LotteryServer.betStatistics.totalBetAmount;
        
        // 遍历所有可能的特码
        for (let tema = 1; tema <= 49; tema++) {
            // 找到该特码的最大亏损组合
            const maxLossCombination = this.findMaxLossCombination(tema);
            
            // 分别计算特码最大亏损和总玩法最大亏损
            const temaMaxLoss = this.calculateTemaMaxLoss(tema, maxLossCombination.zhengma) || 0;
            const totalMaxLoss = maxLossCombination.maxPayout || 0;
            
            // 计算净盈利（基于总玩法最大亏损）
            const netProfit = totalBetAmount - totalMaxLoss;
            
            // 特码计算完成
            
            results.push({
                tema: tema,
                zhengma: maxLossCombination.zhengma,
                netProfit: netProfit,
                temaMaxLoss: temaMaxLoss,
                totalMaxLoss: totalMaxLoss,
                totalBetAmount: totalBetAmount,
                loss: netProfit < 0 ? Math.abs(netProfit) : 0,
                profit: netProfit > 0 ? netProfit : 0
            });
        }
        
        // 按总玩法最大亏损从高到低排序
        results.sort((a, b) => {
            if (a.totalMaxLoss !== b.totalMaxLoss) {
                return b.totalMaxLoss - a.totalMaxLoss;
            }
            return a.tema - b.tema;
        });
        
        // 添加排名
        return results.map((result, index) => ({
            ...result,
            rank: index + 1
        }));
    },

    // 计算特码相关的最大亏损
    calculateTemaMaxLoss(tema, zhengma) {
        if (!window.LotteryServer || !window.LotteryServer.calculateProfitLoss) {
            return 0;
        }
        
        const lotteryResult = {
            tema: tema,
            zhengma: zhengma,
            allNumbers: [tema, ...zhengma]
        };
        
        try {
            const profitLoss = window.LotteryServer.calculateProfitLoss(lotteryResult);
            
            // 只统计特码相关的赔付
            const temaPayout = (profitLoss && profitLoss.details && profitLoss.details.tema) 
                ? profitLoss.details.tema.payout 
                : 0;
            
            // 计算总投注金额
            const totalBetAmount = this.getTotalBetAmount();
            
            // 净盈利 = 总投注 - 赔付
            const netProfit = totalBetAmount - temaPayout;
            
            // 返回净盈利（正数表示盈利，负数表示亏损）
            return netProfit;
        } catch (error) {
            console.error('计算特码最大亏损时出错:', error);
            return 0;
        }
    },

    // 获取总投注金额
    getTotalBetAmount() {
        if (!window.LotteryServer || !window.LotteryServer.betStatistics) {
            return 0;
        }
        return window.LotteryServer.betStatistics.totalBetAmount || 0;
    },

    // 计算特码收到的投注金额
    calculateTemaReceivedAmount(tema) {
        if (!window.LotteryServer || !window.LotteryServer.betStatistics) {
            return 0;
        }
        
        let totalReceived = 0;
        const betStats = window.LotteryServer.betStatistics;
        
        // 所有特码直选投注金额都算收入（不管开出哪个特码）
        if (betStats.temasDirectBets) {
            Object.values(betStats.temasDirectBets).forEach(betData => {
                if (betData && betData.totalAmount) {
                    totalReceived += betData.totalAmount;
                }
            });
        }
        
        // 特码两面投注金额也都算收入
        if (betStats.temasSideBets) {
            Object.values(betStats.temasSideBets).forEach(sideData => {
                if (sideData && sideData.totalAmount) {
                    totalReceived += sideData.totalAmount;
                }
            });
        }
        
        return totalReceived;
    },

    // 计算最大亏损摘要
    calculateMaxLossSummary(lossRankingData) {
        const totalResults = lossRankingData.length;
        const lossResults = lossRankingData.filter(r => r.netProfit < 0);
        const profitResults = lossRankingData.filter(r => r.netProfit > 0);
        const breakEvenResults = lossRankingData.filter(r => r.netProfit === 0);
        
        const maxLoss = lossResults.length > 0 ? Math.max(...lossResults.map(r => Math.abs(r.netProfit))) : 0;
        const avgLoss = lossResults.length > 0 ? lossResults.reduce((sum, r) => sum + Math.abs(r.netProfit), 0) / lossResults.length : 0;
        
        return {
            totalBetAmount: lossRankingData[0]?.totalBetAmount || 0,
            maxLoss: maxLoss,
            avgLoss: avgLoss,
            totalResults: totalResults,
            lossResultsCount: lossResults.length,
            profitResultsCount: profitResults.length,
            breakEvenResultsCount: breakEvenResults.length
        };
    },
    
    // 显示分析报告
    displayAnalysisReport(report) {
        const panel = document.getElementById('lotteryAnalysisPanel');
        const totalBetEl = document.getElementById('analysisTotalBet');
        const profitRateEl = document.getElementById('analysisProfitRate');
        const maxProfitEl = document.getElementById('analysisMaxProfit');
        const maxLossEl = document.getElementById('analysisMaxLoss');
        const topResultsEl = document.getElementById('topResultsTable');
        
        if (panel && totalBetEl && profitRateEl && maxProfitEl && maxLossEl && topResultsEl) {
            // 显示面板
            panel.style.display = 'block';
            
            // 更新汇总数据
            totalBetEl.textContent = `¥${report.totalBetAmount}`;
            profitRateEl.textContent = `${report.profitablePercentage}%`;
            maxProfitEl.textContent = `¥${report.maxProfit}`;
            maxLossEl.textContent = `¥${Math.abs(report.minProfit)}`;
            
            // 生成前10结果表格
            let tableHtml = `
                <div class="top-results-header">
                    <span>排名</span>
                    <span>特码</span>
                    <span>正码</span>
                    <span>总赔付</span>
                    <span>净盈利</span>
                </div>
            `;
            
            report.topResults.slice(0, 10).forEach((result, index) => {
                const profitClass = result.netProfit >= 0 ? 'positive' : 'negative';
                const lotteryResult = result.lotteryResult;
                const profitLoss = result.profitLoss;
                
                tableHtml += `
                    <div class="top-results-row">
                        <span>${index + 1}</span>
                        <span>${lotteryResult.tema.toString().padStart(2, '0')}</span>
                        <span class="zhengma-numbers">${lotteryResult.zhengma.map(n => n.toString().padStart(2, '0')).join(', ')}</span>
                        <span>¥${profitLoss.totalPayout}</span>
                        <span class="profit-value ${profitClass}">¥${result.netProfit}</span>
                    </div>
                `;
            });
            
            topResultsEl.innerHTML = tableHtml;
        }
    },

    // 显示亏损排序
    displayLossRanking(lossRankingData, lossSummary) {
        const panel = document.getElementById('lossRankingPanel');
        const summaryEl = document.getElementById('lossRankingSummary');
        const tableEl = document.getElementById('lossRankingTable');
        
        if (panel && summaryEl && tableEl) {
            // 显示面板
            panel.style.display = 'block';
            
            // 显示摘要信息
            const summaryHtml = `
                <div class="loss-summary-grid">
                    <div class="summary-item">
                        <span class="label">总投注金额:</span>
                        <span class="value">¥${lossSummary.totalBetAmount}</span>
                    </div>
                    <div class="summary-item">
                        <span class="label">最大亏损:</span>
                        <span class="value negative">¥${lossSummary.maxLoss}</span>
                    </div>
                    <div class="summary-item">
                        <span class="label">平均亏损:</span>
                        <span class="value">¥${lossSummary.avgLoss.toFixed(2)}</span>
                    </div>
                    <div class="summary-item">
                        <span class="label">亏损结果数:</span>
                        <span class="value">${lossSummary.lossResultsCount}/${lossSummary.totalResults}</span>
                    </div>
                    <div class="summary-item">
                        <span class="label">盈利结果数:</span>
                        <span class="value positive">${lossSummary.profitResultsCount}/${lossSummary.totalResults}</span>
                    </div>
                    <div class="summary-item">
                        <span class="label">盈亏平衡数:</span>
                        <span class="value">${lossSummary.breakEvenResultsCount}/${lossSummary.totalResults}</span>
                    </div>
                </div>
            `;
            summaryEl.innerHTML = summaryHtml;
            
            // 生成完整排序表格
            let tableHtml = `
                <div class="loss-ranking-count">
                    <span>共 ${lossRankingData.length} 个开奖结果</span>
                </div>
                <div class="loss-ranking-header" id="lossRankingHeader">
                    <span class="rank-col">排名</span>
                    <span class="tema-col">特码</span>
                    <span class="tema-loss-col">特码最大亏损</span>
                    <span class="total-loss-col">总玩法最大亏损</span>
                    <span class="actions-col">操作</span>
                </div>
                <div class="loss-ranking-body">
            `;
            
            // 亏损排序数据生成完成
            
            // 计算颜色分级
            const { lossLevels, profitLevels } = this.calculateColorLevels(lossRankingData);
            
            lossRankingData.forEach((result, index) => {
                const profitClass = result.netProfit >= 0 ? 'positive' : 'negative';
                
                // 计算特码盈亏的颜色等级和显示
                const temaNetProfit = result.temaMaxLoss || 0;
                let colorClass, temaDisplay;
                
                if (temaNetProfit > 0) {
                    // 盈利：绿色
                    colorClass = 'tema-profit';
                    temaDisplay = `+¥${temaNetProfit.toFixed(2)}`;
                } else if (temaNetProfit < 0) {
                    // 亏损：红色，显示为负数
                    const colorLevel = this.getTemaLossColorLevel(Math.abs(temaNetProfit), lossRankingData);
                    colorClass = `tema-loss-level-${colorLevel}`;
                    temaDisplay = `-¥${Math.abs(temaNetProfit).toFixed(2)}`;
                } else {
                    // 盈亏平衡
                    colorClass = 'tema-loss-level-0';
                    temaDisplay = `¥0.00`;
                }
                
                // 总玩法盈亏显示
                const totalLoss = result.totalMaxLoss || 0;
                const totalBetAmount = this.getTotalBetAmount();
                const totalNetProfit = totalBetAmount - totalLoss;
                
                let totalLossDisplay;
                if (totalNetProfit > 0) {
                    // 盈利：显示为正数
                    totalLossDisplay = `+¥${totalNetProfit.toFixed(2)}`;
                } else if (totalNetProfit < 0) {
                    // 亏损：显示为负数
                    totalLossDisplay = `-¥${Math.abs(totalNetProfit).toFixed(2)}`;
                } else {
                    // 盈亏平衡
                    totalLossDisplay = `¥0.00`;
                }
                
                // 添加总玩法盈亏的样式类
                let totalLossClass = '';
                if (totalNetProfit > 0) {
                    totalLossClass = 'total-loss-positive';
                } else if (totalNetProfit < 0) {
                    // 计算总玩法亏损等级
                    const totalLossLevel = this.getTotalLossColorLevel(Math.abs(totalNetProfit), lossRankingData);
                    totalLossClass = `total-loss-level-${totalLossLevel}`;
                } else {
                    totalLossClass = 'total-loss-level-0';
                }
                
                // 获取特码的波色
                const temaColorClass = this.getNumberColor(result.tema);
                
                tableHtml += `
                    <div class="loss-ranking-row ${colorClass} ${totalLossClass}">
                        <span class="rank">${result.rank}</span>
                        <span class="tema ${temaColorClass}">${result.tema.toString().padStart(2, '0')}</span>
                        <span class="tema-loss">${temaDisplay}</span>
                        <span class="total-loss">${totalLossDisplay}</span>
                        <span class="actions">
                            <button class="show-bets-btn" onclick="BankerManager.toggleBetDetails(${result.tema}, [${result.zhengma.join(',')}], this)">
                                详情
                            </button>
                        </span>
                    </div>
                `;
            });
            
            tableHtml += '</div>';
            tableEl.innerHTML = tableHtml;
        }
    },
    
    // 计算颜色分级
    calculateColorLevels(lossRankingData) {
        // 分离亏损和盈利数据
        const lossData = lossRankingData.filter(r => r.netProfit < 0).map(r => Math.abs(r.netProfit));
        const profitData = lossRankingData.filter(r => r.netProfit > 0).map(r => r.netProfit);
        
        // 计算亏损分级（5等分）
        const lossLevels = [];
        if (lossData.length > 0) {
            lossData.sort((a, b) => a - b); // 从小到大排序
            const dataCount = lossData.length;
            
            if (dataCount === 1) {
                // 只有一个数据，所有等级都用这个值
                for (let i = 0; i < 5; i++) {
                    lossLevels.push(lossData[0]);
                }
            } else {
                // 按分位数分级
                for (let i = 0; i < 5; i++) {
                    const index = Math.floor((dataCount - 1) * i / 4);
                    lossLevels.push(lossData[index]);
                }
            }
        }
        
        // 计算盈利分级（5等分）
        const profitLevels = [];
        if (profitData.length > 0) {
            profitData.sort((a, b) => a - b); // 从小到大排序
            const dataCount = profitData.length;
            
            if (dataCount === 1) {
                // 只有一个数据，所有等级都用这个值
                for (let i = 0; i < 5; i++) {
                    profitLevels.push(profitData[0]);
                }
            } else {
                // 按分位数分级
                for (let i = 0; i < 5; i++) {
                    const index = Math.floor((dataCount - 1) * i / 4);
                    profitLevels.push(profitData[index]);
                }
            }
        }
        
        return { lossLevels, profitLevels };
    },
    
    // 获取颜色等级
    getColorLevel(netProfit, lossLevels, profitLevels) {
        if (netProfit < 0) {
            // 亏损：等级1-5，5是最深的红色（亏损最多）
            const absProfit = Math.abs(netProfit);
            if (lossLevels.length === 0) return 1;
            
            for (let i = 4; i >= 0; i--) {
                if (absProfit >= lossLevels[i]) {
                    return i + 1;
                }
            }
            return 1;
        } else if (netProfit > 0) {
            // 盈利：等级1-5，5是最深的绿色（盈利最多）
            if (profitLevels.length === 0) return 1;
            
            for (let i = 4; i >= 0; i--) {
                if (netProfit >= profitLevels[i]) {
                    return i + 1;
                }
            }
            return 1;
        } else {
            // 盈亏平衡
            return 0;
        }
    },

    // 获取特码亏损颜色等级
    getTemaLossColorLevel(temaLossAmount, allResults) {
        if (temaLossAmount <= 0) return 0;
        
        // 获取所有特码亏损数据并排序（只取负数的绝对值）
        const temaLossData = allResults
            .map(r => r.temaMaxLoss || 0)
            .filter(loss => loss < 0)  // 只取亏损的情况
            .map(loss => Math.abs(loss))  // 转为正数
            .sort((a, b) => a - b);
        
        if (temaLossData.length === 0) return 1;
        if (temaLossData.length === 1) return 1;
        
        // 按分位数分级（1-5级）
        const dataCount = temaLossData.length;
        for (let i = 4; i >= 0; i--) {
            const index = Math.floor((dataCount - 1) * i / 4);
            if (temaLossAmount >= temaLossData[index]) {
                return i + 1;
            }
        }
        
        return 1;
    },

    // 获取总玩法亏损颜色等级
    getTotalLossColorLevel(totalLossAmount, allResults) {
        if (totalLossAmount <= 0) return 0;
        
        // 获取所有总玩法亏损数据并排序
        const totalBetAmount = this.getTotalBetAmount();
        const totalLossData = allResults
            .map(r => {
                const netProfit = totalBetAmount - (r.totalMaxLoss || 0);
                return netProfit < 0 ? Math.abs(netProfit) : 0;
            })
            .filter(loss => loss > 0)
            .sort((a, b) => a - b);
        
        if (totalLossData.length === 0) return 1;
        if (totalLossData.length === 1) return 1;
        
        // 按分位数分级（1-5级）
        const dataCount = totalLossData.length;
        for (let i = 4; i >= 0; i--) {
            const index = Math.floor((dataCount - 1) * i / 4);
            if (totalLossAmount >= totalLossData[index]) {
                return i + 1;
            }
        }
        
        return 1;
    },
    
    // 获取号码对应的波色
    getNumberColor(number) {
        // 红波号码
        const redNumbers = [1, 2, 7, 8, 12, 13, 18, 19, 23, 24, 29, 30, 34, 35, 40, 45, 46];
        // 蓝波号码
        const blueNumbers = [3, 4, 9, 10, 14, 15, 20, 25, 26, 31, 36, 37, 41, 42, 47, 48];
        // 绿波号码
        const greenNumbers = [5, 6, 11, 16, 17, 21, 22, 27, 28, 32, 33, 38, 39, 43, 44, 49];
        
        if (redNumbers.includes(number)) return 'red';
        if (blueNumbers.includes(number)) return 'blue';
        if (greenNumbers.includes(number)) return 'green';
        return '';
    },
    
    // 重置开奖服务器
    resetLotteryServer() {
        if (confirm('确定要重置开奖服务器统计数据吗？')) {
            try {
                window.LotteryServer.resetStatistics();
                
                // 隐藏结果面板
                const optimalPanel = document.getElementById('optimalResultPanel');
                const analysisPanel = document.getElementById('lotteryAnalysisPanel');
                const lossRankingPanel = document.getElementById('lossRankingPanel');
                
                if (optimalPanel) optimalPanel.style.display = 'none';
                if (analysisPanel) analysisPanel.style.display = 'none';
                if (lossRankingPanel) lossRankingPanel.style.display = 'none';
                
                this.optimalResult = null;
                
                alert('开奖服务器统计数据已重置！');
            } catch (error) {
                console.error('重置开奖服务器错误:', error);
                alert('重置开奖服务器时发生错误：' + error.message);
            }
        }
    },

    // 计算开奖概率
    calculateLotteryProbability(tema, zhengma) {
        // 检查是否有正码相关的投注
        const hasZhengmaRelatedBets = this.allBets.some(bet => {
            return bet.game === 'zhengma' || 
                   bet.game === 'lianma' ||
                   (bet.game === 'shengxiao' && (bet.sub === 'zhengxiao' || bet.sub === 'yixiao' || bet.sub === 'zongxiao')) ||
                   (bet.game === 'weishu' && bet.sub === 'zhengteweishu') ||
                   bet.game === 'buzhong' ||
                   (bet.game === 'sebo' && bet.sub === 'qisebo');
        });
        
        if (!hasZhengmaRelatedBets) {
            // 如果没有正码相关投注，只考虑特码概率
            return '2.04%';
        }
        
        // 检查是否有特定正码号码的投注
        const specificZhengmaBets = this.allBets.filter(bet => 
            bet.game === 'zhengma' && bet.numbers && bet.numbers.length > 0
        );
        
        if (specificZhengmaBets.length > 0) {
            // 计算正码组合的概率
            // 特码概率：1/49
            // 正码概率：从剩余48个数字中选6个的概率
            
            // 检查当前正码组合是否包含被投注的号码
            const betNumbers = new Set();
            specificZhengmaBets.forEach(bet => {
                bet.numbers.forEach(num => betNumbers.add(num));
            });
            
            const betZhengmaCount = zhengma.filter(num => betNumbers.has(num)).length;
            
            if (betZhengmaCount > 0) {
                // 如果正码中包含被投注的号码，概率会更复杂
                // 这里简化计算：特码概率 × 正码匹配概率
                const temaProbability = 1/49;
                
                // 正码匹配概率的简化计算
                // 实际应该用组合数学计算，这里用近似值
                let zhengmaProbability = 1;
                
                // 从48个数字中选6个，包含特定数字的概率
                // C(包含的数字个数, betZhengmaCount) × C(48-包含的数字个数, 6-betZhengmaCount) / C(48, 6)
                if (betZhengmaCount === 1) {
                    zhengmaProbability = 6/48; // 约12.5%
                } else if (betZhengmaCount === 2) {
                    zhengmaProbability = (6*5)/(48*47); // 约0.33%
                } else if (betZhengmaCount >= 3) {
                    zhengmaProbability = 0.01; // 很小的概率
                }
                
                const totalProbability = temaProbability * zhengmaProbability * 100;
                return totalProbability.toFixed(3) + '%';
            }
        }
        
        // 如果有正码相关投注但没有特定号码投注，或者正码不匹配
        // 返回基础特码概率
        return '2.04%';
    },

    // 格式化正码显示
    formatZhengmaDisplay(zhengma, tema) {
        // 检查是否有正码相关的投注（不包括纯特码直选）
        const hasZhengmaRelatedBets = this.allBets.some(bet => {
            // 正码任选投注
            if (bet.game === 'zhengma') return true;
            
            // 连码投注（依赖正码）
            if (bet.game === 'lianma') return true;
            
            // 生肖投注（部分依赖正码）
            if (bet.game === 'shengxiao' && 
                (bet.sub === 'zhengxiao' || bet.sub === 'yixiao' || bet.sub === 'zongxiao')) return true;
            
            // 尾数投注（部分依赖正码）
            if (bet.game === 'weishu' && bet.sub === 'zhengteweishu') return true;
            
            // 不中投注（依赖正码）
            if (bet.game === 'buzhong') return true;
            
            // 色波投注（部分依赖正码）
            if (bet.game === 'sebo' && bet.sub === 'qisebo') return true;
            
            return false;
        });
        
        if (!hasZhengmaRelatedBets) {
            return '任意6个数（无正码投注）';
        }
        
        // 检查是否有特定的正码投注
        const specificZhengmaBets = this.allBets.filter(bet => 
            bet.game === 'zhengma' && bet.numbers && bet.numbers.length > 0
        );
        
        // 获取被投注的正码号码
        let betNumbers = new Set();
        
        if (window.LotteryServer && window.LotteryServer.betStatistics) {
            // 从 LotteryServer 获取正码投注号码
            Object.keys(window.LotteryServer.betStatistics.zhengmaDirectBets).forEach(number => {
                betNumbers.add(parseInt(number));
            });
        } else if (specificZhengmaBets.length > 0) {
            // 备用方案：从 specificZhengmaBets 获取
            specificZhengmaBets.forEach(bet => {
                bet.numbers.forEach(num => betNumbers.add(num));
            });
        }
            
        if (betNumbers.size > 0) {
            // 检查当前正码中哪些是被投注的
            const betZhengma = zhengma.filter(num => betNumbers.has(num));
            const otherZhengma = zhengma.filter(num => !betNumbers.has(num));
            
            // 高亮显示被投注的号码
            const betDisplay = betZhengma.map(n => `<span class="bet-number">${n.toString().padStart(2, '0')}</span>`).join(', ');
            const otherDisplay = otherZhengma.map(n => n.toString().padStart(2, '0')).join(', ');
            
            if (betZhengma.length > 0 && otherZhengma.length > 0) {
                return `${betDisplay}, ${otherDisplay}`;
            } else if (betZhengma.length > 0) {
                return betDisplay;
            } else {
                return otherDisplay;
            }
        }
        
        // 如果有正码相关投注但没有具体号码投注，显示所有正码
        return zhengma.map(n => n.toString().padStart(2, '0')).join(', ');
    },

    // 使用指定的开奖结果
    useSpecificResult(tema, zhengma) {
        if (confirm(`确定使用此开奖结果吗？\n特码：${tema}\n正码：${zhengma.join(', ')}`)) {
            try {
                // 自动填入开奖输入框
                const temaInput = document.getElementById('tema');
                const zhengmaInputs = [
                    document.getElementById('zhengma1'),
                    document.getElementById('zhengma2'),
                    document.getElementById('zhengma3'),
                    document.getElementById('zhengma4'),
                    document.getElementById('zhengma5'),
                    document.getElementById('zhengma6')
                ];
                
                if (temaInput) {
                    temaInput.value = tema;
                }
                
                zhengmaInputs.forEach((input, index) => {
                    if (input && zhengma[index]) {
                        input.value = zhengma[index];
                    }
                });
                
                // 自动计算实际盈亏
                this.calculateActualResult();
                
                alert('已使用指定开奖结果并自动计算实际盈亏！');
            } catch (error) {
                console.error('使用指定结果错误:', error);
                alert('使用指定结果时发生错误：' + error.message);
            }
        }
    },

    // 切换投注详情显示
    toggleBetDetails(tema, zhengma, buttonElement) {
        const row = buttonElement.closest('.loss-ranking-row');
        let detailsRow = row.nextElementSibling;
        
        // 检查是否已经有详情行
        if (detailsRow && detailsRow.classList.contains('bet-details-row')) {
            // 如果已经展开，则收起
            detailsRow.remove();
            buttonElement.textContent = '详情';
            return;
        }
        
        // 创建详情行
        const detailsHtml = this.generateBetDetailsHtml(tema, zhengma);
        const detailsRowElement = document.createElement('div');
        detailsRowElement.className = 'bet-details-row';
        detailsRowElement.innerHTML = detailsHtml;
        
        // 插入到当前行后面
        row.parentNode.insertBefore(detailsRowElement, row.nextSibling);
        
        // 更新按钮文本
        buttonElement.textContent = '收起';
    },

    // 生成投注详情HTML
    generateBetDetailsHtml(tema, zhengma) {
        // 获取该特码下的所有可能正码组合
        const zhengmaCombinations = this.generateZhengmaCombinations(tema);
        
        let detailsHtml = `
                <div class="bet-details-content">
                    <div class="bet-details-header">
                    <h4>特码 ${tema.toString().padStart(2, '0')} 开奖详情</h4>
                    <span class="winning-count">共 ${zhengmaCombinations.length} 种正码组合</span>
                    </div>
                
                <!-- 正码组合信息表格 -->
                <div class="zhengma-combination-table">
                    <div class="zhengma-combination-header">
                        <span>正码组合</span>
                        <span>概率</span>
                        <span>最大亏损</span>
                        <span>详情</span>
                    </div>
                    <div class="zhengma-combination-body">
        `;
        
        // 为每个正码组合生成一行
        zhengmaCombinations.forEach((combination, index) => {
            const probability = this.calculateLotteryProbability(tema, combination.zhengma);
            const winningBets = this.getWinningBets(tema, combination.zhengma);
            
            // 使用已计算的总赔付，如果没有则重新计算
            const totalPayout = combination.totalPayout !== undefined ? 
                combination.totalPayout : 
                this.calculateCombinationPayout(tema, combination.zhengma);
            
            // 优先显示组合描述，如果没有则显示格式化的正码
            const displayText = combination.description || this.formatZhengmaDisplay(combination.zhengma, tema);
            
            detailsHtml += `
                <div class="zhengma-combination-row">
                    <span class="zhengma-display">${displayText}</span>
                    <span class="probability">${probability}</span>
                    <span class="total-payout">¥${totalPayout.toFixed(2)}</span>
                    <span class="zhengma-actions">
                        <button class="show-zhengma-details-btn" onclick="BankerManager.toggleZhengmaDetails(${tema}, [${combination.zhengma.join(',')}], this)">
                            详情
                        </button>
                    </span>
                </div>
                
                <!-- 中奖投注详情（初始隐藏） -->
                <div class="zhengma-details-content" style="display: none;">
                    ${this.generateWinningBetsTable(winningBets, tema)}
                </div>
            `;
        });
        
        detailsHtml += `
                    </div>
                </div>
            </div>
        `;
        
        return detailsHtml;
    },
    
    // 生成正码组合
    generateZhengmaCombinations(tema) {
        // 检查是否有正码相关投注
        let hasZhengmaRelatedBets = false;
        
        if (window.LotteryServer && window.LotteryServer.betStatistics) {
            const stats = window.LotteryServer.betStatistics;
            hasZhengmaRelatedBets = 
                Object.keys(stats.zhengmaDirectBets).length > 0 ||
                Object.keys(stats.zhengmaSideBets).length > 0 ||
                Object.keys(stats.lianmaBets).length > 0 ||
                Object.keys(stats.buzhongBets).length > 0 ||
                Object.keys(stats.shengxiaoBets).length > 0 ||
                Object.keys(stats.weishuBets).length > 0 ||
                Object.keys(stats.seboBets).length > 0;
        } else {
            // 备用方案
            hasZhengmaRelatedBets = this.allBets.some(bet => {
                return bet.game === 'zhengma' || 
                       bet.game === 'lianma' ||
                       (bet.game === 'shengxiao' && (bet.sub === 'zhengxiao' || bet.sub === 'yixiao' || bet.sub === 'zongxiao')) ||
                       (bet.game === 'weishu' && bet.sub === 'zhengteweishu') ||
                       bet.game === 'buzhong' ||
                       (bet.game === 'sebo' && bet.sub === 'qisebo');
            });
        }
        
        const combinations = [];
        
        if (hasZhengmaRelatedBets) {
            // 获取正码投注信息，区分不同类型
            const zhengmaBetInfo = this.getZhengmaBetInfo();
            
            if (zhengmaBetInfo.hasAnyBets) {
                // 生成所有可能的中奖情况组合
                const winCombinations = this.generateZhengmaWinCombinationsAdvanced(zhengmaBetInfo, tema);
                
                // 为每个组合计算总赔付
                winCombinations.forEach(combination => {
                    const totalPayout = this.calculateCombinationPayout(tema, combination.zhengma);
                    combination.totalPayout = totalPayout;
                });
                
                combinations.push(...winCombinations);
            }
        }
        
        // 无论是否有正码投注，都要生成至少一个组合来计算特码的总赔付
        if (combinations.length === 0) {
            const randomZhengma = this.generateMockZhengma(tema);
            const totalPayout = this.calculateCombinationPayout(tema, randomZhengma);
            combinations.push({
                zhengma: randomZhengma,
                description: hasZhengmaRelatedBets ? '随机组合' : '基础组合（主要为特码投注）',
                totalPayout: totalPayout
            });
        }
        
        // 按亏损从大到小排序（totalPayout越大，亏损越大）
        // 这样可以让庄家优先看到最危险的开奖组合，便于风险控制
        combinations.sort((a, b) => {
            // 优先按总赔付从大到小排序（亏损最大的在前）
            if (b.totalPayout !== a.totalPayout) {
                return b.totalPayout - a.totalPayout;
            }
            // 如果总赔付相同，按描述排序保持稳定性
            return a.description.localeCompare(b.description);
        });
        
        return combinations;
    },

    // 获取正码投注信息，区分不同类型
    getZhengmaBetInfo() {
        const info = {
            hasAnyBets: false,
            anyChoice: [], // 任选投注的号码
            position1: [], // 正1特投注的号码
            position2: [], // 正2特投注的号码
            position3: [], // 正3特投注的号码
            position4: [], // 正4特投注的号码
            position5: [], // 正5特投注的号码
            position6: []  // 正6特投注的号码
        };

        // 从 this.allBets 中获取正码投注信息
        this.allBets.forEach(bet => {
            if (bet.game === 'zhengma' && bet.numbers && bet.numbers.length > 0) {
                info.hasAnyBets = true;
                
                if (bet.sub === 'renxuan') {
                    // 任选投注
                    bet.numbers.forEach(num => {
                        if (!info.anyChoice.includes(num)) {
                            info.anyChoice.push(num);
                        }
                    });
                } else if (bet.sub === 'zheng1te') {
                    // 正1特投注
                    bet.numbers.forEach(num => {
                        if (!info.position1.includes(num)) {
                            info.position1.push(num);
                        }
                    });
                } else if (bet.sub === 'zheng2te') {
                    // 正2特投注
                    bet.numbers.forEach(num => {
                        if (!info.position2.includes(num)) {
                            info.position2.push(num);
                        }
                    });
                } else if (bet.sub === 'zheng3te') {
                    // 正3特投注
                    bet.numbers.forEach(num => {
                        if (!info.position3.includes(num)) {
                            info.position3.push(num);
                        }
                    });
                } else if (bet.sub === 'zheng4te') {
                    // 正4特投注
                    bet.numbers.forEach(num => {
                        if (!info.position4.includes(num)) {
                            info.position4.push(num);
                        }
                    });
                } else if (bet.sub === 'zheng5te') {
                    // 正5特投注
                    bet.numbers.forEach(num => {
                        if (!info.position5.includes(num)) {
                            info.position5.push(num);
                        }
                    });
                } else if (bet.sub === 'zheng6te') {
                    // 正6特投注
                    bet.numbers.forEach(num => {
                        if (!info.position6.includes(num)) {
                            info.position6.push(num);
                        }
                    });
                }
            }
        });

        return info;
    },

    // 生成高级正码中奖组合（区分任选和正N特）
    generateZhengmaWinCombinationsAdvanced(zhengmaBetInfo, tema) {
        // 添加缓存机制，避免重复计算
        const cacheKey = `${tema}_${JSON.stringify(zhengmaBetInfo)}`;
        if (this._combinationCache && this._combinationCache[cacheKey]) {
            return this._combinationCache[cacheKey];
        }
        
        // 使用高级正码组合生成逻辑
        
        const combinations = [];
        
        // 检查是否有多种类型的投注
        const hasMultipleTypes = this.hasMultipleBetTypes(zhengmaBetInfo);
        
        if (hasMultipleTypes) {
            // 如果有多种投注类型，生成复合组合
            combinations.push(...this.generateCompositeCombinations(zhengmaBetInfo, tema));
        } else {
            // 如果只有单一类型，使用原有逻辑
            combinations.push(...this.generateSingleTypeCombinations(zhengmaBetInfo, tema));
        }

        // 如果没有生成任何组合，生成一个默认组合
        if (combinations.length === 0) {
            combinations.push({
                zhengma: this.generateMockZhengma(tema),
                description: '无相关投注组合'
            });
        }

        // 缓存结果
        if (!this._combinationCache) {
            this._combinationCache = {};
        }
        this._combinationCache[cacheKey] = combinations;

        return combinations;
    },

    // 检查是否有多种投注类型
    hasMultipleBetTypes(zhengmaBetInfo) {
        let typeCount = 0;
        
        if (zhengmaBetInfo.anyChoice.length > 0) typeCount++;
        
        for (let position = 1; position <= 6; position++) {
            const positionKey = `position${position}`;
            if (zhengmaBetInfo[positionKey].length > 0) {
                typeCount++;
            }
        }
        
        return typeCount > 1;
    },

    // 生成复合投注的所有可能组合
    generateCompositeCombinations(zhengmaBetInfo, tema) {
        const combinations = [];
        const availableNumbers = [];
        
        // 获取除特码外的所有可用号码
        for (let i = 1; i <= 49; i++) {
            if (i !== tema) {
                availableNumbers.push(i);
            }
        }

        // 收集所有投注类型和对应的号码
        const betTypes = [];
        
        // 任选投注
        if (zhengmaBetInfo.anyChoice.length > 0) {
            zhengmaBetInfo.anyChoice.filter(num => num !== tema).forEach(num => {
                betTypes.push({
                    type: 'anyChoice',
                    number: num,
                    description: `正码任选 ${num.toString().padStart(2, '0')}`
                });
            });
        }
        
        // 正N特投注
        for (let position = 1; position <= 6; position++) {
            const positionKey = `position${position}`;
            const positionNumbers = zhengmaBetInfo[positionKey].filter(num => num !== tema);
            
            positionNumbers.forEach(num => {
                betTypes.push({
                    type: `position${position}`,
                    number: num,
                    position: position,
                    description: `正码正${position}特 ${num.toString().padStart(2, '0')}`
                });
            });
        }

        // 生成所有可能的中奖状态组合（2^n种可能）
        const totalCombinations = Math.pow(2, betTypes.length);
        
        for (let i = 0; i < totalCombinations; i++) {
            const winStates = [];
            const description = [];
            
            // 确定每个投注的中奖状态
            for (let j = 0; j < betTypes.length; j++) {
                const isWinning = (i & (1 << j)) !== 0;
                winStates.push(isWinning);
                
                const betType = betTypes[j];
                if (isWinning) {
                    description.push(`${betType.description} 中`);
                } else {
                    description.push(`${betType.description} 不中`);
                }
            }
            
            // 检查是否存在约束冲突
            const isValidCombination = this.validateWinStatesConstraints(betTypes, winStates);
            
            if (isValidCombination) {
                // 生成对应的正码组合
                const zhengma = this.generateZhengmaForWinStates(betTypes, winStates, availableNumbers, tema);
                
                if (zhengma) {
                    combinations.push({
                        zhengma: zhengma,
                        description: description.join(' + ')
                    });
                }
            }
        }

        return combinations;
    },

    // 验证中奖状态是否存在约束冲突
    validateWinStatesConstraints(betTypes, winStates) {
        // 收集同一号码的不同投注类型和状态
        const numberConstraints = new Map();
        
        for (let i = 0; i < betTypes.length; i++) {
            const betType = betTypes[i];
            const isWinning = winStates[i];
            const number = betType.number;
            
            if (!numberConstraints.has(number)) {
                numberConstraints.set(number, []);
            }
            
            numberConstraints.get(number).push({
                type: betType.type,
                position: betType.position,
                isWinning: isWinning
            });
        }
        
        // 检查每个号码的约束是否冲突
        for (const [number, constraints] of numberConstraints) {
            let mustInclude = false;
            let mustExclude = false;
            const positionRequirements = new Set();
            
            for (const constraint of constraints) {
                if (constraint.type === 'anyChoice') {
                    if (constraint.isWinning) {
                        mustInclude = true; // 任选中奖：必须在正码中
                    } else {
                        mustExclude = true; // 任选不中奖：不能在正码中
                    }
                } else if (constraint.type.startsWith('position')) {
                    if (constraint.isWinning) {
                        positionRequirements.add(constraint.position); // 必须在指定位置
                        mustInclude = true; // 位置投注中奖也意味着必须在正码中
                    }
                    // 位置投注不中奖不会强制排除号码（可能在其他位置）
                }
            }
            
            // 检查冲突：不能既要包含又要排除
            if (mustInclude && mustExclude) {
                return false;
            }
            
            // 检查位置冲突：一个号码不能同时在多个位置
            if (positionRequirements.size > 1) {
                return false;
            }
        }
        
        return true;
    },

    // 生成单一类型投注的组合
    generateSingleTypeCombinations(zhengmaBetInfo, tema) {
        const combinations = [];
        const availableNumbers = [];
        
        // 获取除特码外的所有可用号码
        for (let i = 1; i <= 49; i++) {
            if (i !== tema) {
                availableNumbers.push(i);
            }
        }

        // 为任选投注生成组合
        if (zhengmaBetInfo.anyChoice.length > 0) {
            const anyChoiceNumbers = zhengmaBetInfo.anyChoice.filter(num => num !== tema);
            if (tema <= 3) {
                // 生成任选组合
            }
            const anyChoiceCombinations = this.generateAnyChoiceCombinations(anyChoiceNumbers, availableNumbers, tema);
            if (tema <= 3) {
                // 任选组合生成完成
            }
            combinations.push(...anyChoiceCombinations);
        }

        // 为正N特投注生成组合
        for (let position = 1; position <= 6; position++) {
            const positionKey = `position${position}`;
            const positionNumbers = zhengmaBetInfo[positionKey].filter(num => num !== tema);
            
            if (positionNumbers.length > 0) {
                combinations.push(...this.generatePositionSpecificCombinations(
                    positionNumbers, position, availableNumbers, tema
                ));
            }
        }

        return combinations;
    },

    // 根据中奖状态生成对应的正码组合
    generateZhengmaForWinStates(betTypes, winStates, availableNumbers, tema) {
        const zhengma = [0, 0, 0, 0, 0, 0]; // 6个位置
        const usedNumbers = new Set();
        const mustIncludeNumbers = new Set();
        const mustExcludeNumbers = new Set();
        const positionExclusions = new Map(); // 记录哪些号码不能在哪些位置
        
        // 处理位置特定的投注（正N特）
        for (let i = 0; i < betTypes.length; i++) {
            const betType = betTypes[i];
            const isWinning = winStates[i];
            
            if (betType.type.startsWith('position')) {
                const position = betType.position - 1; // 转换为0-based索引
                
                if (isWinning) {
                    // 必须在指定位置
                    zhengma[position] = betType.number;
                    usedNumbers.add(betType.number);
                } else {
                    // 不能在指定位置，但可能在其他位置
                    if (!positionExclusions.has(betType.number)) {
                        positionExclusions.set(betType.number, new Set());
                    }
                    positionExclusions.get(betType.number).add(position);
                }
            } else if (betType.type === 'anyChoice') {
                if (isWinning) {
                    // 任选中奖：必须包含在正码中
                    mustIncludeNumbers.add(betType.number);
                } else {
                    // 任选不中奖：不能包含在正码中
                    mustExcludeNumbers.add(betType.number);
                }
            }
        }
        
        // 填充剩余位置
        const remainingNumbers = availableNumbers.filter(num => 
            !usedNumbers.has(num) && !mustExcludeNumbers.has(num)
        );
        
        // 先处理任选必须包含的号码
        const mustIncludeArray = Array.from(mustIncludeNumbers).filter(num => !usedNumbers.has(num));
        let includeIndex = 0;
        
        for (let i = 0; i < 6; i++) {
            if (zhengma[i] === 0) {
                let numberToPlace = null;
                
                // 优先放置必须包含的号码
                if (includeIndex < mustIncludeArray.length) {
                    const candidateNumber = mustIncludeArray[includeIndex];
                    // 检查这个号码是否可以放在这个位置
                    if (!positionExclusions.has(candidateNumber) || 
                        !positionExclusions.get(candidateNumber).has(i)) {
                        numberToPlace = candidateNumber;
                        includeIndex++;
                    }
                }
                
                // 如果没有必须包含的号码，或者必须包含的号码不能放在这个位置
                if (numberToPlace === null) {
                    // 找到可以放在这个位置的号码
                    const availableForPosition = remainingNumbers.filter(num => {
                        return !positionExclusions.has(num) || !positionExclusions.get(num).has(i);
                    });
                    
                    if (availableForPosition.length > 0) {
                        const randomIndex = Math.floor(Math.random() * availableForPosition.length);
                        numberToPlace = availableForPosition[randomIndex];
                        // 从remainingNumbers中移除这个号码
                        const indexInRemaining = remainingNumbers.indexOf(numberToPlace);
                        if (indexInRemaining > -1) {
                            remainingNumbers.splice(indexInRemaining, 1);
                        }
                    }
                }
                
                if (numberToPlace !== null) {
                    zhengma[i] = numberToPlace;
                    usedNumbers.add(numberToPlace);
                }
            }
        }
        
        // 确保所有必须包含的号码都被放置
        for (let i = includeIndex; i < mustIncludeArray.length; i++) {
            const numberToPlace = mustIncludeArray[i];
            // 找到可以放置这个号码的位置
            for (let pos = 0; pos < 6; pos++) {
                if (zhengma[pos] === 0 && 
                    (!positionExclusions.has(numberToPlace) || 
                     !positionExclusions.get(numberToPlace).has(pos))) {
                    zhengma[pos] = numberToPlace;
                    usedNumbers.add(numberToPlace);
                    break;
                }
            }
        }
        
        // 确保所有位置都有号码
        for (let i = 0; i < 6; i++) {
            if (zhengma[i] === 0) {
                // 找到可以放在这个位置的号码
                const availableForPosition = remainingNumbers.filter(num => {
                    return !positionExclusions.has(num) || !positionExclusions.get(num).has(i);
                });
                
                if (availableForPosition.length > 0) {
                    const numberToPlace = availableForPosition[0];
                    zhengma[i] = numberToPlace;
                    const indexInRemaining = remainingNumbers.indexOf(numberToPlace);
                    if (indexInRemaining > -1) {
                        remainingNumbers.splice(indexInRemaining, 1);
                    }
                } else if (remainingNumbers.length > 0) {
                    // 如果没有完全符合位置限制的号码，使用任意剩余号码
                    zhengma[i] = remainingNumbers.shift();
                } else {
                    // 如果没有可用号码了，使用一个随机数
                    let randomNum;
                    do {
                        randomNum = Math.floor(Math.random() * 49) + 1;
                    } while (randomNum === tema || usedNumbers.has(randomNum));
                    zhengma[i] = randomNum;
                }
            }
        }
        
        return zhengma; // 不要排序，保持位置信息
    },

    // 生成任选投注的组合
    generateAnyChoiceCombinations(betNumbers, availableNumbers, tema) {
        const combinations = [];
        
        if (betNumbers.length === 0) return combinations;

        // 生成不同中奖情况的组合
        if (betNumbers.length === 1) {
            const betNumber = betNumbers[0];
            const otherNumbers = availableNumbers.filter(n => n !== betNumber);

            // 中奖：投注号码在正码的任意位置（合并显示）
            const winZhengma = [betNumber, ...this.getRandomNumbers(otherNumbers, 5)].sort((a, b) => a - b);
            combinations.push({
                zhengma: winZhengma,
                description: `任选中奖：包含 ${betNumber.toString().padStart(2, '0')}（可在任意位置）`
            });

            // 不中奖：投注号码不在正码中
            const loseCombination = this.getRandomNumbers(otherNumbers, 6).sort((a, b) => a - b);
            combinations.push({
                zhengma: loseCombination,
                description: `任选不中奖：不包含 ${betNumber.toString().padStart(2, '0')}`
            });

        } else {
            // 多个号码的任选投注
            const otherNumbers = availableNumbers.filter(n => !betNumbers.includes(n));

            // 全中：所有投注号码都在正码中
            if (betNumbers.length <= 6) {
                const allWinZhengma = [
                    ...betNumbers,
                    ...this.getRandomNumbers(otherNumbers, 6 - betNumbers.length)
                ].sort((a, b) => a - b);
                
                combinations.push({
                    zhengma: allWinZhengma,
                    description: `任选全中：包含所有号码 ${betNumbers.map(n => n.toString().padStart(2, '0')).join(', ')}`
                });
            }

            // 部分中奖：只有部分投注号码在正码中
            const partialCount = Math.min(Math.floor(betNumbers.length / 2), 3);
            const partialNumbers = betNumbers.slice(0, partialCount);
            const partialWinZhengma = [
                ...partialNumbers,
                ...this.getRandomNumbers(otherNumbers, 6 - partialCount)
            ].sort((a, b) => a - b);
            
            combinations.push({
                zhengma: partialWinZhengma,
                description: `任选部分中奖：包含 ${partialNumbers.map(n => n.toString().padStart(2, '0')).join(', ')}`
            });

            // 全不中：所有投注号码都不在正码中
            const allLoseZhengma = this.getRandomNumbers(otherNumbers, 6).sort((a, b) => a - b);
            combinations.push({
                zhengma: allLoseZhengma,
                description: `任选全不中：不包含任何投注号码`
            });
        }

        return combinations;
    },

    // 生成正N特投注的组合
    generatePositionSpecificCombinations(betNumbers, position, availableNumbers, tema) {
        const combinations = [];
        
        if (betNumbers.length === 0) return combinations;

        const positionIndex = position - 1; // 转换为0-based索引
        
        betNumbers.forEach(betNumber => {
            const otherNumbers = availableNumbers.filter(n => n !== betNumber);

            // 中奖：投注号码在指定位置
            const winZhengma = this.getRandomNumbers(otherNumbers, 6);
            winZhengma[positionIndex] = betNumber;
            winZhengma.sort((a, b) => a - b);
            
            combinations.push({
                zhengma: winZhengma,
                description: `正${position}特中奖：${betNumber.toString().padStart(2, '0')} 在第${position}位`
            });

            // 不中奖：投注号码不在指定位置（但可能在其他位置）
            const loseZhengma1 = this.getRandomNumbers(otherNumbers, 6).sort((a, b) => a - b);
            combinations.push({
                zhengma: loseZhengma1,
                description: `正${position}特不中奖：${betNumber.toString().padStart(2, '0')} 不在第${position}位`
            });
        });

        return combinations;
    },

    // 计算指定正码组合的总赔付
    /**
     * 计算指定特码和正码组合的总赔付金额
     * @param {number} tema - 特码号码
     * @param {Array<number>} zhengma - 正码组合数组
     * @returns {number} 总赔付金额
     */
    calculateCombinationPayout(tema, zhengma) {
        try {
            const winningBets = this.getWinningBets(tema, zhengma);
            let totalPayout = 0;
            
            for (const bet of winningBets) {
                const winAmount = this.calculateWinPayout(bet, tema);
                totalPayout += winAmount;
            }
            
            return totalPayout;
        } catch (error) {
            console.error('计算组合赔付时出错:', error);
            return 0;
        }
    },

    /**
     * 找到产生最大亏损的正码组合
     * @param {number} tema - 特码号码
     * @returns {Object} 包含最大亏损正码组合和赔付金额的对象
     */
    findMaxLossCombination(tema) {
        const zhengmaBetInfo = this.getZhengmaBetInfo();
        const combinations = this.generateZhengmaWinCombinationsAdvanced(zhengmaBetInfo, tema);
        
        if (combinations.length === 0) {
            return {
                zhengma: this.generateMockZhengma(tema),
                maxPayout: 0
            };
        }
        
        // 找出赔付最高的组合（即最大亏损）
        let maxPayout = 0;
        let maxLossCombination = combinations[0];
        
        for (const combination of combinations) {
            const payout = this.calculateCombinationPayout(tema, combination.zhengma);
            if (payout > maxPayout) {
                maxPayout = payout;
                maxLossCombination = combination;
            }
        }
        
        return {
            zhengma: maxLossCombination.zhengma || this.generateMockZhengma(tema),
            maxPayout: maxPayout || 0
        };
    },
    
    // 生成正码中奖组合
    generateZhengmaWinCombinations(betNumbers, tema) {
        const combinations = [];
        
        // 获取除特码外的所有可用号码
        const availableNumbers = [];
        for (let i = 1; i <= 49; i++) {
            if (i !== tema) {
                availableNumbers.push(i);
            }
        }
        
        // 根据投注号码数量生成不同的中奖情况
        if (betNumbers.length === 1) {
            // 单个号码投注：中奖 vs 不中奖
            const betNumber = betNumbers[0];
            
            // 情况1：中奖（投注号码在正码中）
            const otherNumbers = availableNumbers.filter(n => n !== betNumber);
            const winCombination = [betNumber, ...this.getRandomNumbers(otherNumbers, 5)].sort((a, b) => a - b);
            combinations.push({
                zhengma: winCombination,
                description: `中奖：包含 ${betNumber.toString().padStart(2, '0')}`
            });
            
            // 情况2：不中奖（投注号码不在正码中）
            const loseCombination = this.getRandomNumbers(otherNumbers, 6).sort((a, b) => a - b);
            combinations.push({
                zhengma: loseCombination,
                description: `不中奖：不包含 ${betNumber.toString().padStart(2, '0')}`
            });
            
        } else if (betNumbers.length === 2) {
            // 两个号码投注：全中、中A不中B、中B不中A、全不中
            const [numA, numB] = betNumbers;
            const otherNumbers = availableNumbers.filter(n => !betNumbers.includes(n));
            
            // 情况1：全中（A和B都在正码中）
            const bothWinCombination = [numA, numB, ...this.getRandomNumbers(otherNumbers, 4)].sort((a, b) => a - b);
            combinations.push({
                zhengma: bothWinCombination,
                description: `全中：包含 ${numA.toString().padStart(2, '0')}, ${numB.toString().padStart(2, '0')}`
            });
            
            // 情况2：中A不中B
            const winACombination = [numA, ...this.getRandomNumbers(otherNumbers, 5)].sort((a, b) => a - b);
            combinations.push({
                zhengma: winACombination,
                description: `中 ${numA.toString().padStart(2, '0')} 不中 ${numB.toString().padStart(2, '0')}`
            });
            
            // 情况3：中B不中A
            const winBCombination = [numB, ...this.getRandomNumbers(otherNumbers, 5)].sort((a, b) => a - b);
            combinations.push({
                zhengma: winBCombination,
                description: `中 ${numB.toString().padStart(2, '0')} 不中 ${numA.toString().padStart(2, '0')}`
            });
            
            // 情况4：全不中
            const bothLoseCombination = this.getRandomNumbers(otherNumbers, 6).sort((a, b) => a - b);
            combinations.push({
                zhengma: bothLoseCombination,
                description: `全不中：不包含 ${numA.toString().padStart(2, '0')}, ${numB.toString().padStart(2, '0')}`
            });
            
        } else if (betNumbers.length >= 3) {
            // 三个或更多号码投注：生成主要的几种情况
            const otherNumbers = availableNumbers.filter(n => !betNumbers.includes(n));
            
            // 情况1：全中（所有投注号码都在正码中，如果超过6个则取前6个）
            if (betNumbers.length <= 6) {
                const needCount = 6 - betNumbers.length;
                const allWinCombination = [...betNumbers, ...this.getRandomNumbers(otherNumbers, needCount)].sort((a, b) => a - b);
                combinations.push({
                    zhengma: allWinCombination,
                    description: `全中：包含所有投注号码`
                });
            } else {
                const allWinCombination = betNumbers.slice(0, 6).sort((a, b) => a - b);
                combinations.push({
                    zhengma: allWinCombination,
                    description: `全中：包含前6个投注号码`
                });
            }
            
            // 情况2：部分中奖（只包含部分投注号码）
            const partialCount = Math.min(Math.floor(betNumbers.length / 2), 3);
            const partialNumbers = betNumbers.slice(0, partialCount);
            const needCount = 6 - partialCount;
            const partialWinCombination = [...partialNumbers, ...this.getRandomNumbers(otherNumbers, needCount)].sort((a, b) => a - b);
            combinations.push({
                zhengma: partialWinCombination,
                description: `部分中奖：包含 ${partialNumbers.map(n => n.toString().padStart(2, '0')).join(', ')}`
            });
            
            // 情况3：全不中
            const allLoseCombination = this.getRandomNumbers(otherNumbers, 6).sort((a, b) => a - b);
            combinations.push({
                zhengma: allLoseCombination,
                description: `全不中：不包含任何投注号码`
            });
        }
        
        return combinations;
    },
    
    // 从数组中随机选择指定数量的数字
    getRandomNumbers(numbers, count) {
        const shuffled = [...numbers].sort(() => Math.random() - 0.5);
        return shuffled.slice(0, Math.min(count, shuffled.length));
    },
    
    // 生成中奖投注表格
    generateWinningBetsTable(winningBets, tema) {
        if (winningBets.length === 0) {
            return `
                <div class="no-winning-bets">
                    <p>该开奖结果下没有中奖投注</p>
                </div>
            `;
        }
        
        let tableHtml = `
                <div class="winning-bets-table">
                    <div class="winning-bets-header">
                        <span>投注ID</span>
                        <span>玩法</span>
                        <span>投注内容</span>
                        <span>注数</span>
                        <span>单注金额</span>
                        <span>总金额</span>
                        <span>赔率</span>
                        <span>中奖金额</span>
                    </div>
                    <div class="winning-bets-body">
        `;
        
        winningBets.forEach(bet => {
            const gameText = this.getGameText(bet.game, bet.sub);
            const contentText = this.getBetContentText(bet);
            // 使用统一的中奖赔付计算方法，传入特码号码处理和局
            const winAmount = this.calculateWinPayout(bet, tema);
            
            tableHtml += `
                <div class="winning-bet-row">
                    <span class="bet-id">${bet.bankerId ? bet.bankerId.substr(-6) : 'N/A'}</span>
                    <span class="game-type">${gameText}</span>
                    <span class="bet-content">${contentText}</span>
                    <span class="bet-count">${bet.count}</span>
                    <span class="single-amount">¥${bet.amount}</span>
                    <span class="total-amount">¥${bet.amount * bet.count}</span>
                    <span class="odds">${bet.odds}</span>
                    <span class="win-amount">¥${winAmount}</span>
                </div>
            `;
        });
        
        tableHtml += `
                </div>
            </div>
        `;
        
        return tableHtml;
    },
    
    // 切换正码详情显示
    toggleZhengmaDetails(tema, zhengma, buttonElement) {
        const detailsContent = buttonElement.closest('.zhengma-combination-row').nextElementSibling;
        
        if (detailsContent.style.display === 'none') {
            detailsContent.style.display = 'block';
            buttonElement.textContent = '收起';
        } else {
            detailsContent.style.display = 'none';
            buttonElement.textContent = '详情';
        }
    },

    // 获取中奖投注
    /**
     * 获取指定开奖结果下的中奖投注列表
     * @param {number} tema - 特码号码
     * @param {Array<number>} zhengma - 正码组合数组
     * @returns {Array} 中奖投注列表
     */
    getWinningBets(tema, zhengma) {
        const winningBets = [];
        
        // 确保 allBets 数组存在且有效
        if (!this.allBets || !Array.isArray(this.allBets)) {
            return winningBets;
        }
        
        try {
            for (const bet of this.allBets) {
                if (!bet) {
                    continue;
                }
                
            const isWinning = this.isBetWinning(bet, tema, zhengma);
            
            if (isWinning) {
                winningBets.push(bet);
            }
            }
        } catch (error) {
            console.error('查找中奖投注时出错:', error);
        }
        
        return winningBets;
    },

    // 判断投注是否中奖
    isBetWinning(bet, tema, zhengma) {
        // 构造正确的开奖数据格式
        const drawData = {
            temaNumber: tema,
            zhengmaNumbers: zhengma,
            allNumbers: [tema, ...zhengma]
        };
        
        return this.checkBetWinActual(bet, drawData);
    },

    // 获取玩法文本
    getGameText(game, sub) {
        const gameTexts = {
            'tema': {
                'zhixuan': '特码直选',
                'liangmian': '特码两面'
            },
            'zhengma': {
                'renxuan': '正码任选',
                'yite': '正码1特',
                'liangmian': '正码1两面'
            },
            'lianma': {
                'erquanzhong': '二全中',
                'sanquanzhong': '三全中',
                'erzhongte': '二中特',
                'sanzhonger': '三中二',
                'techuan': '特串'
            },
            'shengxiao': {
                'texiao': '特肖',
                'zhengxiao': '正肖',
                'yixiao': '一肖',
                'zongxiao': '总肖',
                'sanxiaolian': '三肖连',
                'erxiaolian': '二肖连',
                'sixiaolian': '四肖连',
                'hexiaozhong': '合肖中',
                'hexiaobuzhong': '合肖不中'
            },
            'weishu': {
                'zhengteweishu': '正特尾数',
                'tematouwei': '特码头尾',
                'erweilianzhong': '二尾连中',
                'sanweilianzhong': '三尾连中',
                'siweilianzhong': '四尾连中'
            },
            'buzhong': {
                'wubuzhong': '五不中',
                'liubuzhong': '六不中',
                'qibuzhong': '七不中',
                'babuzhong': '八不中',
                'jiubuzhong': '九不中',
                'shibuzhong': '十不中'
            },
            'sebo': {
                'qisebo': '七色波'
            },
            'banbo': {
                'temabanbo': '特码半波'
            }
        };
        
        return gameTexts[game]?.[sub] || `${game}-${sub}`;
    },

    // 获取投注内容文本
    getBetContentText(bet) {
        if (bet.numbers && bet.numbers.length > 0) {
            return bet.numbers.map(n => n.toString().padStart(2, '0')).join(', ');
        }
        
        if (bet.animals && bet.animals.length > 0) {
            return bet.animals.join(', ');
        }
        
        if (bet.tails && bet.tails.length > 0) {
            return bet.tails.join('尾, ') + '尾';
        }
        
        if (bet.sideType) {
            return this.getSideTypeDisplayName(bet.sideType);
        }
        
        if (bet.sebo && bet.sebo.length > 0) {
            return bet.sebo.join(', ');
        }
        
        if (bet.selectedBanbos && bet.selectedBanbos.length > 0) {
            return bet.selectedBanbos.join(', ');
        }
        
        return bet.description || '未知';
    },

    // 获取两面投注类型的中文显示名称
    getSideTypeDisplayName(sideType) {
        const sideTypeNames = {
            'da': '大',
            'xiao': '小',
            'dan': '单',
            'shuang': '双',
            'dadan': '大单',
            'dashuang': '大双',
            'xiaodan': '小单',
            'xiaoshuang': '小双',
            'heda': '合大',
            'hexiao': '合小',
            'hedan': '合单',
            'heshuang': '合双',
            'weida': '尾大',
            'weixiao': '尾小',
            'jiaqin': '家禽',
            'yeshou': '野兽',
            'hongbo': '红波',
            'red': '红波',
            'lanbo': '蓝波',
            'blue': '蓝波',
            'lvbo': '绿波',
            'green': '绿波',
            'he': '和'
        };
        
        return sideTypeNames[sideType] || sideType;
    },
    
    // 使用最优结果开奖
    useOptimalResult() {
        if (!this.optimalResult) {
            alert('请先计算最优开奖结果！');
            return;
        }
        
        const lotteryResult = this.optimalResult.lotteryResult;
        const netProfit = this.optimalResult.netProfit;
        
        if (confirm(`确定使用最优开奖结果吗？\n特码：${lotteryResult.tema}\n正码：${lotteryResult.zhengma.join(', ')}\n净盈利：¥${netProfit}`)) {
            try {
                // 自动填入开奖输入框
                const temaInput = document.getElementById('tema');
                const zhengmaInputs = [
                    document.getElementById('zhengma1'),
                    document.getElementById('zhengma2'),
                    document.getElementById('zhengma3'),
                    document.getElementById('zhengma4'),
                    document.getElementById('zhengma5'),
                    document.getElementById('zhengma6')
                ];
                
                if (temaInput) {
                    temaInput.value = lotteryResult.tema;
                }
                
                zhengmaInputs.forEach((input, index) => {
                    if (input && lotteryResult.zhengma[index]) {
                        input.value = lotteryResult.zhengma[index];
                    }
                });
                
                // 自动计算实际盈亏
                this.calculateActualResult();
                
                alert('已使用最优开奖结果并自动计算实际盈亏！');
            } catch (error) {
                console.error('使用最优结果错误:', error);
                alert('使用最优结果时发生错误：' + error.message);
            }
        }
    },
    
    // 转换投注格式为lottery-server期望的格式
    convertBetForLotteryServer(bet) {
        const betDetails = [];
        
        // 特码直选多选：每个号码单独一注，每注金额为10元
        if (bet.game === 'tema' && bet.sub === 'zhixuan' && bet.numbers && bet.numbers.length > 1) {
            // 特码直选多选：每个号码都是单独的10元投注
            bet.numbers.forEach(number => {
                betDetails.push({
                    type: this.getBetTypeForLotteryServer(bet),
                    game: bet.game,
                    sub: bet.sub,
                    amount: 10, // 每注固定10元
                    odds: bet.odds,
                    numbers: [number], // 每个号码单独投注
                    animals: bet.animals,
                    tails: bet.tails,
                    heads: bet.heads,
                    sideType: bet.sideType,
                    position: bet.position,
                    sebo: bet.sebo,
                    banboType: bet.banboType,
                    selectedBanbos: bet.selectedBanbos,
                    zongxiaoType: bet.zongxiaoType,
                    description: `[特码,特码直选] ${number.toString().padStart(2, '0')}`,
                    originalBetId: bet.bankerId
                });
            });
        } else {
            // 其他投注类型：根据count属性，生成对应数量的单个投注记录
            for (let i = 0; i < bet.count; i++) {
                betDetails.push({
                    type: this.getBetTypeForLotteryServer(bet),
                    game: bet.game,
                    sub: bet.sub,
                    amount: bet.amount, // 单注金额
                    odds: bet.odds,
                    numbers: bet.numbers,
                    animals: bet.animals,
                    tails: bet.tails,
                    heads: bet.heads,
                    sideType: bet.sideType,
                    position: bet.position,
                    sebo: bet.sebo,
                    banboType: bet.banboType,
                    selectedBanbos: bet.selectedBanbos,
                    zongxiaoType: bet.zongxiaoType,
                    description: bet.description,
                    originalBetId: bet.bankerId
                });
            }
        }
        
        return {
            betDetails: betDetails
        };
    },
    
    // 获取lottery-server期望的投注类型
    getBetTypeForLotteryServer(bet) {
        // 根据banker.js的投注数据确定lottery-server期望的类型
        if (bet.game === 'tema' && bet.sub === 'zhixuan') return 'direct';
        if (bet.game === 'zhengma' && bet.sub === 'renxuan') return 'direct';
        if (bet.game === 'zhengma' && bet.sub === 'zheng1te') return 'direct';
        if (bet.game === 'zhengma' && bet.sub === 'zheng2te') return 'direct';
        if (bet.game === 'zhengma' && bet.sub === 'zheng3te') return 'direct';
        if (bet.game === 'zhengma' && bet.sub === 'zheng4te') return 'direct';
        if (bet.game === 'zhengma' && bet.sub === 'zheng5te') return 'direct';
        if (bet.game === 'zhengma' && bet.sub === 'zheng6te') return 'direct';
        if (bet.game === 'tema' && bet.sub === 'liangmian') return 'sides';
        if (bet.sideType) return 'sides';
        if (bet.game === 'lianma') return 'lianma';
        if (bet.game === 'shengxiao') return 'shengxiao';
        if (bet.game === 'weishu') return 'weishu';
        if (bet.game === 'buzhong') return 'buzhong';
        if (bet.game === 'sebo') return 'sebo';
        if (bet.game === 'banbo') return 'banbo';
        if (bet.zongxiaoType) return 'zongxiao';
        
        // 默认返回direct
        return 'direct';
    },

    // 生成测试数据（用于调试）
    generateTestData() {
        // 清空现有数据
        this.allBets = [];
        
        // 清空localStorage中的数据，避免旧数据干扰
        localStorage.removeItem('banker_all_bets');
        
        // 添加测试投注数据
        const testBets = [
            // 特码直选单选投注
            {
                type: 'numbers',
                game: 'tema',
                sub: 'zhixuan',
                description: '[特码,特码直选] 01',
                amount: 10,
                count: 1,
                odds: 48.5,
                numbers: [1],
                timestamp: Date.now(),
                bankerId: 'test_1'
            },
            // 特码直选多选投注（5个号码）
            {
                type: 'numbers',
                game: 'tema',
                sub: 'zhixuan',
                description: '[特码,特码直选] 02,03,04,05,06',
                amount: 10, // 注意：这里是每注10元，总共50元
                count: 5,   // 5注
                odds: 48.5,
                numbers: [2, 3, 4, 5, 6],
                timestamp: Date.now(),
                bankerId: 'test_2'
            },
            // 特码直选多选投注（3个号码）
            {
                type: 'numbers',
                game: 'tema',
                sub: 'zhixuan',
                description: '[特码,特码直选] 39,40,41',
                amount: 10, // 注意：这里是每注10元，总共30元
                count: 3,   // 3注
                odds: 48.5,
                numbers: [39, 40, 41],
                timestamp: Date.now(),
                bankerId: 'test_3'
            },
            // 特码两面投注
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]大',
                amount: 10,
                count: 1,
                odds: 1.98,
                sideType: 'da',
                timestamp: Date.now(),
                bankerId: 'test_4'
            },
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]家禽',
                amount: 10,
                count: 1,
                odds: 1.979,
                sideType: 'jiaqin',
                timestamp: Date.now(),
                bankerId: 'test_5'
            },
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]野兽',
                amount: 10,
                count: 1,
                odds: 1.900,
                sideType: 'yeshou',
                timestamp: Date.now(),
                bankerId: 'test_6'
            },
            // 合小投注（数字相加≤6）
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]合小',
                amount: 10,
                count: 1,
                odds: 1.980,
                sideType: 'hexiao',
                timestamp: Date.now(),
                bankerId: 'test_7'
            },
            // 合大投注（数字相加>6）
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]合大',
                amount: 10,
                count: 1,
                odds: 1.980,
                sideType: 'heda',
                timestamp: Date.now(),
                bankerId: 'test_8'
            },
            // 合单投注（数字相加为奇数）
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]合单',
                amount: 10,
                count: 1,
                odds: 1.980,
                sideType: 'hedan',
                timestamp: Date.now(),
                bankerId: 'test_9'
            },
            // 合双投注（数字相加为偶数）
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]合双',
                amount: 10,
                count: 1,
                odds: 1.980,
                sideType: 'heshuang',
                timestamp: Date.now(),
                bankerId: 'test_10'
            },
            // 特码两面 - 大（特码49时和局退本）
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]大（49和局）',
                amount: 100,
                count: 1,
                odds: 1.95,
                sideType: 'da',
                timestamp: Date.now(),
                bankerId: 'test_he_da'
            },
            // 特码两面 - 单（特码49时和局退本）
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]单（49和局）',
                amount: 80,
                count: 1,
                odds: 1.95,
                sideType: 'dan',
                timestamp: Date.now(),
                bankerId: 'test_he_dan'
            },
            // 特码两面 - 野兽（特码49时正常算，49是蛇）
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]野兽（49正常算）',
                amount: 50,
                count: 1,
                odds: 1.9,
                sideType: 'yeshou',
                timestamp: Date.now(),
                bankerId: 'test_49_yeshou'
            },
            // 特码两面 - 红波
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]红波',
                amount: 20,
                count: 1,
                odds: 2.98,
                sideType: 'hongbo',
                timestamp: Date.now(),
                bankerId: 'test_hongbo'
            },
            // 特码两面 - 蓝波
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]蓝波',
                amount: 30,
                count: 1,
                odds: 2.98,
                sideType: 'lanbo',
                timestamp: Date.now(),
                bankerId: 'test_lanbo'
            },
            // 特码两面 - 绿波（特码49时正常中奖）
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]绿波（49正常中奖）',
                amount: 25,
                count: 1,
                odds: 2.98,
                sideType: 'lvbo',
                timestamp: Date.now(),
                bankerId: 'test_49_lvbo'
            },
            // 特码两面 - 大单
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]大单',
                amount: 15,
                count: 1,
                odds: 3.96,
                sideType: 'dadan',
                timestamp: Date.now(),
                bankerId: 'test_dadan'
            },
            // 特码两面 - 大双
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]大双',
                amount: 20,
                count: 1,
                odds: 3.96,
                sideType: 'dashuang',
                timestamp: Date.now(),
                bankerId: 'test_dashuang'
            },
            // 特码两面 - 小单
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]小单',
                amount: 10,
                count: 1,
                odds: 3.96,
                sideType: 'xiaodan',
                timestamp: Date.now(),
                bankerId: 'test_xiaodan'
            },
            // 特码两面 - 小双
            {
                type: 'sides',
                game: 'tema',
                sub: 'liangmian',
                description: '[特码,特码两面]小双',
                amount: 12,
                count: 1,
                odds: 3.96,
                sideType: 'xiaoshuang',
                timestamp: Date.now(),
                bankerId: 'test_xiaoshuang'
            },
            // 正码任选投注
            {
                type: 'numbers',
                game: 'zhengma',
                sub: 'renxuan',
                description: '[正码,任选] 02',
                amount: 20,
                count: 1,
                odds: 7.5,
                numbers: [2],
                timestamp: Date.now(),
                bankerId: 'test_zhengma_renxuan'
            },
            // 正1特投注
            {
                type: 'numbers',
                game: 'zhengma',
                sub: 'zheng1te',
                description: '[正码,正1特] 02',
                amount: 15,
                count: 1,
                odds: 47.5,
                numbers: [2],
                timestamp: Date.now(),
                bankerId: 'test_zhengma_zheng1te'
            },
            // 正码任选投注（多个号码）
            {
                type: 'numbers',
                game: 'zhengma',
                sub: 'renxuan',
                description: '[正码,任选] 10,11,12',
                amount: 10,
                count: 3,
                odds: 7.5,
                numbers: [10, 11, 12],
                timestamp: Date.now(),
                bankerId: 'test_zhengma_renxuan_multi'
            },
            // 正2特投注
            {
                type: 'numbers',
                game: 'zhengma',
                sub: 'zheng2te',
                description: '[正码,正2特] 15',
                amount: 25,
                count: 1,
                odds: 47.5,
                numbers: [15],
                timestamp: Date.now(),
                bankerId: 'test_zhengma_zheng2te'
            }
        ];
        
        this.allBets = testBets;
        this.saveBetsToStorage();
        this.updateDisplay();
        
        console.log('测试数据已生成:', testBets.length, '个投注');
        console.log('总投注金额计算：10+50+30+10+10+10+10+10+10+10+100+80+50+20+30+25+15+20+10+12+20+15+30+25=632元');
        alert('测试数据已生成！包含特码直选、两面投注和正码任选、正N特测试\n总投注金额：¥632（包含和局、波色、大小单双、正码任选、正N特测试）');
    },

    // 快速测试亏损排序功能
    quickTestLossRanking() {
        console.log('=== 开始快速测试亏损排序功能 ===');
        
        // 重置LotteryServer
        if (typeof window.LotteryServer !== 'undefined') {
            window.LotteryServer.resetStatistics();
            
            // 添加投注到统计
            this.allBets.forEach(bet => {
                const convertedBet = this.convertBetForLotteryServer(bet);
                console.log('转换后的投注:', convertedBet);
                window.LotteryServer.addBetToStatistics(convertedBet);
            });
            
            console.log('投注统计:', window.LotteryServer.betStatistics);
            
            // 测试特定开奖结果
            const testResults = [1, 2, 3, 39, 25]; // 测试几个特码
            
            testResults.forEach(tema => {
                // 生成一个简单的开奖结果
                const lotteryResult = {
                    tema: tema,
                    zhengma: [10, 11, 12, 13, 14, 15], // 固定正码（避免与特码重复）
                    allNumbers: [tema, 10, 11, 12, 13, 14, 15]
                };
                
                const profitLoss = window.LotteryServer.calculateProfitLoss(lotteryResult);
                const netProfit = window.LotteryServer.betStatistics.totalBetAmount - profitLoss.totalPayout;
                
                console.log(`\n特码${tema}开奖:`);
                console.log(`  总投注: ¥${window.LotteryServer.betStatistics.totalBetAmount}`);
                console.log(`  总赔付: ¥${profitLoss.totalPayout.toFixed(2)}`);
                console.log(`  净盈利: ¥${netProfit.toFixed(2)}`);
                
                // 详细分析
                if (tema === 1) {
                    console.log('  特码1中奖分析：');
                    console.log('    - 特码直选01: 10元 × 48.5 = 485元');
                    console.log('    - 特码两面大: 10元 × 1.98 = 19.8元（1不算大）');
                    console.log('    - 特码两面蓝波: 10元 × 2.98 = 29.8元（1不是蓝波）');
                    console.log('    - 预期总赔付: 485元');
                } else if (tema === 2) {
                    console.log('  特码2中奖分析：');
                    console.log('    - 特码直选02: 10元 × 48.5 = 485元');
                    console.log('    - 特码两面大: 10元 × 1.98 = 19.8元（2不算大）');
                    console.log('    - 特码两面蓝波: 10元 × 2.98 = 29.8元（2不是蓝波）');
                    console.log('    - 预期总赔付: 485元');
                } else if (tema === 39) {
                    console.log('  特码39中奖分析：');
                    console.log('    - 特码直选39: 10元 × 48.5 = 485元');
                    console.log('    - 特码两面大: 10元 × 1.98 = 19.8元（39算大）');
                    console.log('    - 特码两面蓝波: 10元 × 2.98 = 29.8元（39是绿波不是蓝波）');
                    console.log('    - 预期总赔付: 485 + 19.8 = 504.8元');
                }
                
                console.log(`  逻辑检查: ${profitLoss.totalPayout === 0 && netProfit > 0 ? '✅正确' : profitLoss.totalPayout > 0 ? '✅有中奖' : '❌错误'}`);
            });
            
        } else {
            console.error('LotteryServer未定义');
            alert('错误：LotteryServer未加载');
        }
    },

    // 测试合小、合大、合单、合双的计算逻辑
    // 测试特码49和局功能
    testHejuCalculation() {
        console.log('=== 测试特码49和局功能 ===');
        
        // 首先验证49对应的生肖
        const shengxiao49 = CommonUtils.getShengxiao(49);
        console.log(`特码49对应的生肖: ${shengxiao49}`);
        console.log(`49是否为家禽: ${this.isJiaqin(49)}`);
        console.log(`49是否为野兽: ${this.isYeshou(49)}`);
        
        // 测试特码49的各种情况
        const testCases = [
            {
                sideType: 'da',
                expected: 'he',
                description: '大（和局）'
            },
            {
                sideType: 'xiao',
                expected: 'he',
                description: '小（和局）'
            },
            {
                sideType: 'dan',
                expected: 'he',
                description: '单（和局）'
            },
            {
                sideType: 'shuang',
                expected: 'he',
                description: '双（和局）'
            },
            {
                sideType: 'dadan',
                expected: 'he',
                description: '大单（和局）'
            },
            {
                sideType: 'dashuang',
                expected: 'he',
                description: '大双（和局）'
            },
            {
                sideType: 'xiaodan',
                expected: 'he',
                description: '小单（和局）'
            },
            {
                sideType: 'xiaoshuang',
                expected: 'he',
                description: '小双（和局）'
            },
            {
                sideType: 'heda',
                expected: 'he',
                description: '合大（和局）'
            },
            {
                sideType: 'hexiao',
                expected: 'he',
                description: '合小（和局）'
            },
            {
                sideType: 'hedan',
                expected: 'he',
                description: '合单（和局）'
            },
            {
                sideType: 'heshuang',
                expected: 'he',
                description: '合双（和局）'
            },
            {
                sideType: 'jiaqin',
                expected: false,
                description: '家禽（正常算，49是蛇，不是家禽）'
            },
            {
                sideType: 'yeshou',
                expected: true,
                description: '野兽（正常算，49是蛇，属于野兽）'
            },
            {
                sideType: 'hongbo',
                expected: false,
                description: '红波（正常算，49不是红波）'
            },
            {
                sideType: 'red',
                expected: false,
                description: '红波（正常算，49不是红波）'
            },
            {
                sideType: 'lanbo',
                expected: false,
                description: '蓝波（正常算，49不是蓝波）'
            },
            {
                sideType: 'blue',
                expected: false,
                description: '蓝波（正常算，49不是蓝波）'
            },
            {
                sideType: 'lvbo',
                expected: true,
                description: '绿波（正常算，49是绿波）'
            },
            {
                sideType: 'green',
                expected: true,
                description: '绿波（正常算，49是绿波）'
            }
        ];
        
        testCases.forEach(testCase => {
            const bet = {
                sideType: testCase.sideType,
                game: 'tema',
                sub: 'liangmian'
            };
            
            const result = this.checkTemaLiangmianWin(bet, 49);
            const passed = result === testCase.expected;
            
            console.log(`${testCase.description}: ${passed ? '✓' : '✗'} (期望: ${testCase.expected}, 实际: ${result})`);
            
            if (!passed) {
                console.error(`测试失败: ${testCase.description}`);
            }
        });
        
        // 测试赔付计算
        console.log('\n=== 测试和局赔付计算 ===');
        
        const hejuBet = {
            sideType: 'da',
            game: 'tema',
            sub: 'liangmian',
            amount: 100,
            count: 1,
            odds: 1.95
        };
        
        const normalPayout = this.calculateWinPayout(hejuBet, 25); // 正常中奖
        const hejuPayout = this.calculateWinPayout(hejuBet, 49);   // 和局
        
        console.log(`正常中奖赔付 (特码25): ¥${normalPayout} (期望: ¥${100 * 1.95})`);
        console.log(`和局赔付 (特码49): ¥${hejuPayout} (期望: ¥${100})`);
        
        alert('特码49和局功能测试完成！请查看控制台输出结果。');
    },

    testHeCalculation() {
        console.log('=== 测试合小、合大、合单、合双计算 ===');
        
        const testNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 19, 23, 28, 34, 39, 45, 49];
        
        testNumbers.forEach(num => {
            const sum = Math.floor(num / 10) + (num % 10);
            const isHexiao = sum <= 6;
            const isHeda = sum > 6;
            const isHedan = sum % 2 === 1;
            const isHeshuang = sum % 2 === 0;
            
            console.log(`号码${num.toString().padStart(2, '0')}: 合=${sum}, 合小=${isHexiao}, 合大=${isHeda}, 合单=${isHedan}, 合双=${isHeshuang}`);
        });
        
        // 测试特定号码
        console.log('\n=== 特定测试 ===');
        const testBet = { sideType: 'hexiao' };
        
        [1, 3, 5, 6, 7, 15, 24, 39].forEach(num => {
            const result = this.checkTemaLiangmianWin(testBet, num);
            const sum = Math.floor(num / 10) + (num % 10);
            console.log(`特码${num}合小投注: 合=${sum}, 结果=${result}`);
        });
    }
};

// 简化的LotteryServer（临时解决方案）
const SimpleLotteryServer = {
    betStatistics: {
        temasDirectBets: {},
        temasSideBets: {},
        totalBetAmount: 0
    },

    resetBetStatistics() {
        this.betStatistics = {
            temasDirectBets: {},
            temasSideBets: {},
            totalBetAmount: 0
        };
    },

    addBetToStatistics(betData) {
        betData.betDetails.forEach(bet => {
            this.betStatistics.totalBetAmount += bet.amount;
            
            if (bet.type === 'direct' && bet.game === 'tema') {
                if (bet.numbers && bet.numbers.length > 0) {
                    // 现在每个bet.numbers已经只包含一个号码，每注金额就是bet.amount
                    bet.numbers.forEach(number => {
                        if (!this.betStatistics.temasDirectBets[number]) {
                            this.betStatistics.temasDirectBets[number] = {
                                totalAmount: 0,
                                bets: []
                            };
                        }
                        this.betStatistics.temasDirectBets[number].totalAmount += bet.amount;
                        this.betStatistics.temasDirectBets[number].bets.push(bet);
                    });
                }
            } else if (bet.type === 'sides' && bet.game === 'tema') {
                const key = bet.sideType;
                if (!this.betStatistics.temasSideBets[key]) {
                    this.betStatistics.temasSideBets[key] = {
                        totalAmount: 0,
                        bets: [],
                        sideType: bet.sideType
                    };
                }
                this.betStatistics.temasSideBets[key].totalAmount += bet.amount;
                this.betStatistics.temasSideBets[key].bets.push(bet);
            }
        });
    },

    calculateProfitLoss(lotteryResult) {
        let totalPayout = 0;
        const details = { tema: { payout: 0, details: [] } };

        // 特码直选赔付
        if (this.betStatistics.temasDirectBets[lotteryResult.tema]) {
            const betData = this.betStatistics.temasDirectBets[lotteryResult.tema];
            let directPayout = 0;
            betData.bets.forEach(bet => {
                // 特码直选：每个号码都是单独的投注，只需要计算单注的中奖金额
                directPayout += bet.amount * bet.odds;
            });
            totalPayout += directPayout;
            details.tema.payout += directPayout;
        }

        // 特码两面赔付
        Object.entries(this.betStatistics.temasSideBets).forEach(([key, betData]) => {
            if (this.checkSideWin(lotteryResult.tema, betData.sideType)) {
                let sidesPayout = 0;
                betData.bets.forEach(bet => {
                    sidesPayout += bet.amount * bet.odds;
                });
                totalPayout += sidesPayout;
                details.tema.payout += sidesPayout;
            }
        });

        return { totalPayout, details };
    },

    checkSideWin(number, sideType) {
        const colorConfig = {
            blue: [3, 4, 9, 10, 14, 15, 20, 25, 26, 31, 36, 37, 41, 42, 47, 48]
        };

        switch(sideType) {
            case 'da': return number >= 25;
            case 'xiao': return number <= 24;
            case 'lanbo': return colorConfig.blue.includes(number);
            default: return false;
        }
    },

    getAllResultsSortedByLoss() {
        const results = [];
        
        for (let tema = 1; tema <= 49; tema++) {
            const lotteryResult = { tema, zhengma: [2, 3, 4, 5, 6, 7] };
            const profitLoss = this.calculateProfitLoss(lotteryResult);
            const netProfit = this.betStatistics.totalBetAmount - profitLoss.totalPayout;
            
            results.push({
                rank: 0,
                tema,
                zhengma: lotteryResult.zhengma,
                netProfit,
                totalPayout: profitLoss.totalPayout,
                totalBetAmount: this.betStatistics.totalBetAmount,
                loss: netProfit < 0 ? Math.abs(netProfit) : 0,
                profit: netProfit > 0 ? netProfit : 0,
                profitLossDetails: profitLoss.details
            });
        }
        
        // 按净盈利从低到高排序，净盈利相同时按特码号码从低到高排序
        return results.sort((a, b) => {
            if (a.netProfit !== b.netProfit) {
                return a.netProfit - b.netProfit;
            }
            return a.tema - b.tema;
        }).map((result, index) => ({
            ...result,
            rank: index + 1
        }));
    },

    getLossStatisticsSummary() {
        const allResults = this.getAllResultsSortedByLoss();
        const lossResults = allResults.filter(r => r.netProfit < 0);
        const profitResults = allResults.filter(r => r.netProfit > 0);
        const breakEvenResults = allResults.filter(r => r.netProfit === 0);
        
        // 计算最大亏损和平均亏损
        const maxLoss = lossResults.length > 0 ? Math.max(...lossResults.map(r => Math.abs(r.netProfit))) : 0;
        const avgLoss = lossResults.length > 0 ? lossResults.reduce((sum, r) => sum + Math.abs(r.netProfit), 0) / lossResults.length : 0;
        
        return {
            totalResults: allResults.length,
            totalBetAmount: this.betStatistics.totalBetAmount,
            lossResultsCount: lossResults.length,
            profitResultsCount: profitResults.length,
            breakEvenResultsCount: breakEvenResults.length,
            maxLoss: maxLoss,
            avgLoss: avgLoss,
            lossPercentage: (lossResults.length / allResults.length * 100).toFixed(2),
            profitPercentage: (profitResults.length / allResults.length * 100).toFixed(2)
        };
    }
};

// 如果原来的LotteryServer不存在，使用简化版本
if (typeof window.LotteryServer === 'undefined') {
    window.LotteryServer = SimpleLotteryServer;
}

// 将BankerManager添加到全局作用域，以便HTML中的onclick可以访问
window.BankerManager = BankerManager; 